Mirror: TypeScript LSP plugin that finds GraphQL documents in your code and provides diagnostics, auto-complete and hover-information.

Support changing operationName (#40)

* Support changing operationName

* Apply suggestions from code review

Co-authored-by: Jovi De Croock <decroockjovi@gmail.com>

---------

Co-authored-by: Jovi De Croock <decroockjovi@gmail.com>

Daniel b537b682 e7a0ba51

Changed files
+31 -10
packages
graphqlsp
src
+31 -10
packages/graphqlsp/src/index.ts
···
const exportName = isFragment
? `${name}FragmentDoc`
: `${name}Document`;
-
const imp = ` as typeof import('./${nameParts
.join('.')
.replace('.ts', '')}').${exportName}`;
···
const span = { length: 1, start: node.end };
-
// TODO: if we have a typeImport but the name has been updated/is wrong
-
// we need to leave the "as x" typecast
-
const text =
-
source.text.substring(0, span.start) +
-
imp +
-
source.text.substring(
-
span.start + span.length,
-
source.text.length
-
);
const scriptInfo =
info.project.projectService.getScriptInfo(filename);
const snapshot = scriptInfo!.getSnapshot();
···
source.update(text, { span, newLength: imp.length });
scriptInfo!.editContent(0, snapshot.getLength(), text);
info.languageServiceHost.writeFile!(source.fileName, text);
scriptInfo!.registerFileUpdate();
// script info contains a lot of utils that might come in handy here
// to save even if the user has local changes, if we could make that work
···
const exportName = isFragment
? `${name}FragmentDoc`
: `${name}Document`;
+
let imp = ` as typeof import('./${nameParts
.join('.')
.replace('.ts', '')}').${exportName}`;
···
const span = { length: 1, start: node.end };
+
let text = '';
+
if (typeImport) {
+
// We only want the oldExportName here to be present
+
// that way we can diff its length vs the new one
+
const oldExportName = typeImport
+
.getText()
+
.split('.')
+
.pop()
+
+
// Remove ` as ` from the beginning,
+
// this because getText() gives us everything
+
// but ` as ` meaning we need to keep that part
+
// around.
+
imp = imp.slice(4);
+
text = source.text.replace(typeImport.getText(), imp);
+
span.length = imp.length + ((oldExportName || '').length - exportName.length);
+
} else {
+
text =
+
source.text.substring(0, span.start) +
+
imp +
+
source.text.substring(
+
span.start + span.length,
+
source.text.length
+
);
+
}
+
const scriptInfo =
info.project.projectService.getScriptInfo(filename);
const snapshot = scriptInfo!.getSnapshot();
···
source.update(text, { span, newLength: imp.length });
scriptInfo!.editContent(0, snapshot.getLength(), text);
info.languageServiceHost.writeFile!(source.fileName, text);
+
if (!!typeImport) {
+
// To update the types, otherwise data is stale
+
scriptInfo!.reloadFromFile();
+
}
scriptInfo!.registerFileUpdate();
// script info contains a lot of utils that might come in handy here
// to save even if the user has local changes, if we could make that work