mirror of
https://github.com/BradNut/gQuery
synced 2025-09-08 17:40:18 +00:00
lots of updates, need to clean up the repo still
This commit is contained in:
parent
be5afed139
commit
eb63167291
26 changed files with 420 additions and 214067 deletions
47
README.md
47
README.md
|
|
@ -20,23 +20,52 @@ export const g = new GFetch({
|
|||
|
||||
### 2. Add GraphQL Codegen Plugin
|
||||
|
||||
docs coming soon
|
||||
```
|
||||
svelte.config.js
|
||||
|
||||
### 3. Add Codegen Config
|
||||
import gQueryCodegen from '@leveluptuts/g-query/codegen'
|
||||
|
||||
docs coming soon
|
||||
...
|
||||
plugins: [
|
||||
gQueryCodegen({
|
||||
schema: './src/lib/graphql/schema.graphql', // path to schema, schema is required
|
||||
output: './src/lib/graphql', // Where you want the general schema types to output
|
||||
gPath: '$lib/config/g' //Path to g, created in step 1.
|
||||
})
|
||||
],
|
||||
...
|
||||
```
|
||||
|
||||
### 3. Add .graphql files
|
||||
|
||||
```
|
||||
UserQueries.graphql
|
||||
|
||||
query user {
|
||||
user {
|
||||
_id
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
```
|
||||
|
||||
### 4. Use that thang
|
||||
|
||||
The code gen will find the file and spit out a file next to it. Named `FileName.gGenerated.ts`
|
||||
Using the above code, it would output `UserQueries.gGenerated.ts`
|
||||
This also gives us a `get` function for queries based on the query name. ie `getUser` for the above.
|
||||
|
||||
```
|
||||
<script context="module" lang="ts">
|
||||
// The generated function that fetches and caches
|
||||
import { getSeriesList } from '../whatever'
|
||||
import { getUser } from '../whatever'
|
||||
|
||||
export async function load() {
|
||||
export async function load({fetch}) {
|
||||
// Runs the cache/fetch function populating $gCache before use.
|
||||
await getSeriesList({
|
||||
limit: 0
|
||||
await getUser({
|
||||
variables: { limit: 0 },
|
||||
fetch
|
||||
})
|
||||
return {}
|
||||
}
|
||||
|
|
@ -44,9 +73,9 @@ docs coming soon
|
|||
|
||||
<script lang="ts">
|
||||
// Cache becomes populated with data available for SSR
|
||||
import { gCache } from '@leveluptuts/g-query'
|
||||
import { user } from './UserQueries.gGenerated.graphql'
|
||||
|
||||
// $: console.log($gCache.seriesList)
|
||||
// $: console.log($user) //data available for ssr
|
||||
</script>
|
||||
|
||||
```
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@
|
|||
"allowSyntheticDefaultImports": true,
|
||||
"baseUrl": ".",
|
||||
"checkJs": true,
|
||||
"declaration": true,
|
||||
"esModuleInterop": true,
|
||||
"forceConsistentCasingInFileNames": true,
|
||||
"importsNotUsedAsValues": "error",
|
||||
|
|
|
|||
2
codegen/codegen.d.ts
vendored
Normal file
2
codegen/codegen.d.ts
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
import { PluginFunction } from "@graphql-codegen/plugin-helpers";
|
||||
export declare const plugin: PluginFunction<any>;
|
||||
|
|
@ -1,10 +1,8 @@
|
|||
import { visit, concatAST, Kind, } from "graphql";
|
||||
import "@graphql-codegen/plugin-helpers";
|
||||
import { ClientSideBaseVisitor, } from "@graphql-codegen/visitor-plugin-common";
|
||||
import { pascalCase } from "pascal-case";
|
||||
console.log("codegen.ts");
|
||||
import { ClientSideBaseVisitor } from "@graphql-codegen/visitor-plugin-common";
|
||||
import pascalCase from "just-pascal-case";
|
||||
export const plugin = (schema, documents, config) => {
|
||||
console.log("config", config);
|
||||
const allAst = concatAST(documents.map((d) => d.document));
|
||||
const allFragments = [
|
||||
...allAst.definitions.filter((d) => d.kind === Kind.FRAGMENT_DEFINITION).map((fragmentDef) => ({
|
||||
|
|
@ -37,26 +35,37 @@ interface CacheFunctionOptions {
|
|||
const ops = operations
|
||||
.map((o) => {
|
||||
var _a;
|
||||
console.log("o", o.selectionSet.selections);
|
||||
if (o) {
|
||||
const name = ((_a = o === null || o === void 0 ? void 0 : o.name) === null || _a === void 0 ? void 0 : _a.value) || "";
|
||||
// const dsl = `export const ${pascalCase(op.name.value)}Doc = gql\`
|
||||
// ${documents.find((d) => d.rawSDL.includes(`${op.operation} ${op.name.value}`)).rawSDL}\``
|
||||
const op = `${pascalCase(name)}${pascalCase(o.operation)}`;
|
||||
const pascalName = pascalCase(name);
|
||||
const opv = `${op}Variables`;
|
||||
let operations = "";
|
||||
if (o.operation === "query") {
|
||||
operations += `
|
||||
export const ${name}Store = writable()
|
||||
|
||||
export const ${name} = ({ variables, fetch}: FetchWrapperArgs<${opv}>):
|
||||
Promise<GFetchReturnWithErrors<${op}>> =>
|
||||
g.fetch<${op}>({
|
||||
queries: [{ query: ${pascalCase(name)}Doc, variables }],
|
||||
queries: [{ query: ${pascalName}Doc, variables }],
|
||||
fetch
|
||||
})
|
||||
|
||||
|
||||
// Cached
|
||||
export async function get${pascalCase(name)}(variables, options?: CacheFunctionOptions) {
|
||||
await gQuery('user', { query: ${name}, variables }, options)
|
||||
export async function get${pascalCase(name)}({ fetch, variables }: GGetParameters<${opv}>, options?: CacheFunctionOptions) {
|
||||
const data = await g.fetch<${op}>({
|
||||
queries: [{ query: ${pascalName}Doc, variables }],
|
||||
fetch
|
||||
})
|
||||
await ${name}Store.set({ ...data})
|
||||
|
||||
|
||||
await gQuery(${name}, { query: ${name}, variables }, options)
|
||||
}
|
||||
|
||||
`;
|
||||
|
|
@ -66,7 +75,7 @@ export const ${name} = ({ variables, fetch}: FetchWrapperArgs<${opv}>):
|
|||
export const ${name}Subscribe = ({ variables }: SubscribeWrapperArgs<${opv}>):
|
||||
Readable<GFetchReturnWithErrors<${op}>> =>
|
||||
g.oFetch<${op}>({
|
||||
queries: [{ query: ${pascalCase(name)}Doc, variables }]
|
||||
queries: [{ query: ${pascalName}Doc, variables }]
|
||||
})
|
||||
`;
|
||||
}
|
||||
|
|
@ -76,7 +85,7 @@ Readable<GFetchReturnWithErrors<${op}>> =>
|
|||
export const ${name} = ({ variables }: SubscribeWrapperArgs<${opv}>):
|
||||
Promise<GFetchReturnWithErrors<${op}>> =>
|
||||
g.fetch<${op}>({
|
||||
queries: [{ query: ${pascalCase(name)}Doc, variables }],
|
||||
queries: [{ query: ${pascalName}Doc, variables }],
|
||||
fetch,
|
||||
})
|
||||
`;
|
||||
|
|
@ -87,8 +96,9 @@ Promise<GFetchReturnWithErrors<${op}>> =>
|
|||
.join("\n");
|
||||
const imports = [
|
||||
`import type { Readable } from "svelte/store"`,
|
||||
`import { writable } from "svelte/store"`,
|
||||
`import { g } from '${config.gPath}'`,
|
||||
`import type { GFetchReturnWithErrors } from '@leveluptuts/g-query'`,
|
||||
`import type { GFetchReturnWithErrors, GGetParameters } from '@leveluptuts/g-query'`,
|
||||
`import { gQuery } from '@leveluptuts/g-query'`,
|
||||
`import gql from "graphql-tag"`,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
{"version":3,"file":"codegen.js","sourceRoot":"","sources":["codegen.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,EAEL,SAAS,EACT,IAAI,GAGL,MAAM,SAAS,CAAC;AACjB,OAAsC,iCAAiC,CAAC;AACxE,OAAO,EAEL,qBAAqB,GACtB,MAAM,wCAAwC,CAAC;AAEhD,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AAEzC,OAAO,CAAC,GAAG,CAAC,YAAY,CAAC,CAAC;AAE1B,MAAM,CAAC,MAAM,MAAM,GAAwB,CACzC,MAAqB,EACrB,SAA+B,EAC/B,MAAM,EACN,EAAE;IACF,OAAO,CAAC,GAAG,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;IAC9B,MAAM,MAAM,GAAG,SAAS,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC;IAE3D,MAAM,YAAY,GAAqB;QACrC,GACE,MAAM,CAAC,WAAW,CAAC,MAAM,CACvB,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,IAAI,KAAK,IAAI,CAAC,mBAAmB,CAE7C,CAAC,GAAG,CAAC,CAAC,WAAW,EAAE,EAAE,CAAC,CAAC;YACtB,IAAI,EAAE,WAAW;YACjB,IAAI,E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AI,2CAA2C,GAAG;iCAChC,EAAE;WACxB,EAAE;uBACU,UAAU;;;CAGhC,CAAC;aACO;YAED,OAAO,UAAU,CAAC;SACnB;IACH,CAAC,CAAC;SACD,IAAI,CAAC,IAAI,CAAC,CAAC;IAEd,MAAM,OAAO,GAAG;QACd,8CAA8C;QAC9C,yCAAyC;QACzC,sBAAsB,MAAM,CAAC,KAAK,GAAG;QACrC,oFAAoF;QACpF,+CAA+C;QAC/C,+BAA+B;KAChC,CAAC;IAEF,6FAA6F;IAC7F,sDAAsD;IACtD,SAAS;IACT,gCAAgC;IAChC,sBAAsB;IACtB,qCAAqC;IACrC,wBAAwB;IACxB,wDAAwD;IACxD,wBAAwB;IACxB,gEAAgE;IAChE,uDAAuD;IACvD,wBAAwB;IACxB,+GAA+G;IAC/G,wBAAwB;IACxB,wBAAwB;IACxB,wDAAwD;IACxD,mCAAmC;IACnC,0BAA0B;IAE1B,mBAAmB;IACnB,sBAAsB;IACtB,+GAA+G;IAC/G,IAAI;IACJ,MAAM;IACN,WAAW;IACX,oBAAoB;IACpB,oCAAoC;IAEpC,OAAO;QACL,OAAO,EAAE,OAAO;QAChB,OAAO,EAAE;YACP,YAAY;YACZ,OAAO,CAAC,SAAS;YACjB,GAAG,aAAa,CAAC,WAAW,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,OAAO,CAAC,IAAI,QAAQ,CAAC;YAChE,GAAG;SACJ,CAAC,IAAI,CAAC,IAAI,CAAC;KACb,CAAC;AACJ,CAAC,CAAC"}
|
||||
|
|
@ -7,24 +7,17 @@ import {
|
|||
OperationDefinitionNode,
|
||||
} from "graphql";
|
||||
import { Types, PluginFunction } from "@graphql-codegen/plugin-helpers";
|
||||
import {
|
||||
LoadedFragment,
|
||||
ClientSideBaseVisitor,
|
||||
} from "@graphql-codegen/visitor-plugin-common";
|
||||
|
||||
import { pascalCase } from "pascal-case";
|
||||
|
||||
console.log("codegen.ts");
|
||||
import { ClientSideBaseVisitor } from "@graphql-codegen/visitor-plugin-common";
|
||||
import pascalCase from "just-pascal-case";
|
||||
|
||||
export const plugin: PluginFunction<any> = (
|
||||
schema: GraphQLSchema,
|
||||
documents: Types.DocumentFile[],
|
||||
config
|
||||
) => {
|
||||
console.log("config", config);
|
||||
const allAst = concatAST(documents.map((d) => d.document));
|
||||
|
||||
const allFragments: LoadedFragment[] = [
|
||||
const allFragments = [
|
||||
...(
|
||||
allAst.definitions.filter(
|
||||
(d) => d.kind === Kind.FRAGMENT_DEFINITION
|
||||
|
|
@ -50,6 +43,7 @@ export const plugin: PluginFunction<any> = (
|
|||
const operations = allAst.definitions.filter(
|
||||
(d) => d.kind === Kind.OPERATION_DEFINITION
|
||||
) as OperationDefinitionNode[];
|
||||
|
||||
const defaultTypes = `
|
||||
|
||||
type FetchWrapperArgs<T> = {
|
||||
|
|
@ -74,24 +68,32 @@ interface CacheFunctionOptions {
|
|||
// const dsl = `export const ${pascalCase(op.name.value)}Doc = gql\`
|
||||
// ${documents.find((d) => d.rawSDL.includes(`${op.operation} ${op.name.value}`)).rawSDL}\``
|
||||
const op = `${pascalCase(name)}${pascalCase(o.operation)}`;
|
||||
const pascalName = pascalCase(name);
|
||||
const opv = `${op}Variables`;
|
||||
let operations = "";
|
||||
|
||||
if (o.operation === "query") {
|
||||
operations += `
|
||||
export const ${name}Store = writable()
|
||||
|
||||
export const ${name} = ({ variables, fetch}: FetchWrapperArgs<${opv}>):
|
||||
Promise<GFetchReturnWithErrors<${op}>> =>
|
||||
g.fetch<${op}>({
|
||||
queries: [{ query: ${pascalCase(name)}Doc, variables }],
|
||||
queries: [{ query: ${pascalName}Doc, variables }],
|
||||
fetch
|
||||
})
|
||||
|
||||
|
||||
// Cached
|
||||
export async function get${pascalCase(
|
||||
name
|
||||
)}(variables, options?: CacheFunctionOptions) {
|
||||
await gQuery('user', { query: ${name}, variables }, options)
|
||||
// Cached
|
||||
export async function get${pascalCase(
|
||||
name
|
||||
)}({ fetch, variables }: GGetParameters<${opv}>, options?: CacheFunctionOptions) {
|
||||
const data = await g.fetch<${op}>({
|
||||
queries: [{ query: ${pascalName}Doc, variables }],
|
||||
fetch
|
||||
})
|
||||
await ${name}Store.set({ ...data})
|
||||
await gQuery(${name}, { query: ${name}, variables }, options)
|
||||
}
|
||||
|
||||
`;
|
||||
|
|
@ -101,7 +103,7 @@ export const ${name} = ({ variables, fetch}: FetchWrapperArgs<${opv}>):
|
|||
export const ${name}Subscribe = ({ variables }: SubscribeWrapperArgs<${opv}>):
|
||||
Readable<GFetchReturnWithErrors<${op}>> =>
|
||||
g.oFetch<${op}>({
|
||||
queries: [{ query: ${pascalCase(name)}Doc, variables }]
|
||||
queries: [{ query: ${pascalName}Doc, variables }]
|
||||
})
|
||||
`;
|
||||
}
|
||||
|
|
@ -110,7 +112,7 @@ Readable<GFetchReturnWithErrors<${op}>> =>
|
|||
export const ${name} = ({ variables }: SubscribeWrapperArgs<${opv}>):
|
||||
Promise<GFetchReturnWithErrors<${op}>> =>
|
||||
g.fetch<${op}>({
|
||||
queries: [{ query: ${pascalCase(name)}Doc, variables }],
|
||||
queries: [{ query: ${pascalName}Doc, variables }],
|
||||
fetch,
|
||||
})
|
||||
`;
|
||||
|
|
@ -123,40 +125,13 @@ Promise<GFetchReturnWithErrors<${op}>> =>
|
|||
|
||||
const imports = [
|
||||
`import type { Readable } from "svelte/store"`,
|
||||
`import { writable } from "svelte/store"`,
|
||||
`import { g } from '${config.gPath}'`,
|
||||
`import type { GFetchReturnWithErrors } from '@leveluptuts/g-query'`,
|
||||
`import type { GFetchReturnWithErrors, GGetParameters } from '@leveluptuts/g-query'`,
|
||||
`import { gQuery } from '@leveluptuts/g-query'`,
|
||||
`import gql from "graphql-tag"`,
|
||||
];
|
||||
|
||||
// let schemaInputs = getCachedDocumentNodeFromSchema(schema).definitions.filter((d) => {
|
||||
// return d.kind === 'InputObjectTypeDefinition'
|
||||
// })
|
||||
// let inputs = schemaInputs
|
||||
// .map((d) => {
|
||||
// console.log('/* START */')
|
||||
// // @ts-ignore
|
||||
// console.log('NAME: ', d.fields[0].name.value)
|
||||
// // @ts-ignore
|
||||
// let isReq = d.fields[0]?.type?.kind === 'NonNullType'
|
||||
// console.log('REQUIRED: ', isReq ? '✅' : '❌')
|
||||
// // @ts-ignore
|
||||
// console.log('TYPE: ', isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value)
|
||||
// // @ts-ignore
|
||||
// // @ts-ignore
|
||||
// console.log('d.fields[0]', d.fields[0]?.type)
|
||||
// console.log('/* END */')
|
||||
// console.log('')
|
||||
|
||||
// return `
|
||||
// const inputName = {
|
||||
// ${d.fields[0].name.value}: ${isReq ? d.fields[0]?.type?.type?.name?.value : d.fields[0]?.type?.name?.value}
|
||||
// }
|
||||
// `
|
||||
// })
|
||||
// .join('\n')
|
||||
// console.log('inputs', inputs)
|
||||
|
||||
return {
|
||||
prepend: imports,
|
||||
content: [
|
||||
|
|
|
|||
20041
codegen/dist/codegen.js
vendored
20041
codegen/dist/codegen.js
vendored
File diff suppressed because it is too large
Load diff
193882
codegen/dist/plugin.js
vendored
193882
codegen/dist/plugin.js
vendored
File diff suppressed because one or more lines are too long
5
codegen/plugin.d.ts
vendored
Normal file
5
codegen/plugin.d.ts
vendored
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
export default function levelupViteCodegen(options: any): {
|
||||
name: string;
|
||||
buildStart(): Promise<void>;
|
||||
transform(src: any, id: any): void;
|
||||
};
|
||||
|
|
@ -1,28 +1,5 @@
|
|||
import { generate } from "@graphql-codegen/cli";
|
||||
// import { fileURLToPath } from "url";
|
||||
// import { buildSchema, printSchema, parse, GraphQLSchema } from "graphql";
|
||||
// import * as fs from "fs";
|
||||
// import * as path from "path";
|
||||
// import * as typescriptPlugin from "@graphql-codegen/typescript";
|
||||
// const __filename = fileURLToPath(import.meta.url);
|
||||
// const __dirname = path.dirname(__filename);
|
||||
// const schema: GraphQLSchema = buildSchema(`type A { name: String }`);
|
||||
const outputFile = "gquery.generated.ts";
|
||||
// const config = {
|
||||
// documents: [],
|
||||
// config: {}, // used by a plugin internally, although the 'typescript' plugin currently // returns the string output, rather than writing to a file
|
||||
// filename: outputFile,
|
||||
// schema: parse(printSchema(schema)),
|
||||
// plugins: [
|
||||
// // Each plugin should be an object
|
||||
// {
|
||||
// typescript: {}, // Here you can pass configuration to the plugin
|
||||
// },
|
||||
// ],
|
||||
// pluginMap: {
|
||||
// typescript: typescriptPlugin,
|
||||
// },
|
||||
// };
|
||||
const fileRegex = /\.(graphql)$/;
|
||||
export default function levelupViteCodegen(options) {
|
||||
if (!options.schema) {
|
||||
|
|
|
|||
|
|
@ -1 +1 @@
|
|||
{"version":3,"file":"plugin.js","sourceRoot":"","sources":["plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,uCAAuC;AAEvC,4EAA4E;AAC5E,4BAA4B;AAC5B,gCAAgC;AAChC,mEAAmE;AAEnE,qDAAqD;AACrD,8CAA8C;AAE9C,wEAAwE;AACxE,MAAM,UAAU,GAAG,qBAAqB,CAAC;AACzC,mBAAmB;AACnB,mBAAmB;AACnB,wJAAwJ;AACxJ,0BAA0B;AAC1B,wCAAwC;AACxC,eAAe;AACf,yCAAyC;AACzC,QAAQ;AACR,yEAAyE;AACzE,SAAS;AACT,OAAO;AACP,iBAAiB;AACjB,oCAAoC;AACpC,OAAO;AACP,KAAK;AAEL,MAAM,SAAS,GAAG,cAAc,CAAC;AAEjC,MAAM,CAAC,OAAO,UAAU,kBAAkB,CAAC,OAAO;IAChD,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE;QACnB,MAAM,IAAI,KAAK,CAAC,oBAAoB,CAAC,CAAC;KACvC;IACD,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE;QACnB,MAAM,IAAI,KAAK,CAAC,+BAA+B,CAAC,CAAC;KAClD;IACD,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE;QAClB,MAAM,IAAI,KAAK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AAC;QAED,SAAS,CAAC,GAAG,EAAE,EAAE,IAAG,CAAC;KACtB,CAAC;AACJ,CAAC"}
|
||||
|
|
@ -1,33 +1,5 @@
|
|||
import { generate } from "@graphql-codegen/cli";
|
||||
// import { fileURLToPath } from "url";
|
||||
|
||||
// import { buildSchema, printSchema, parse, GraphQLSchema } from "graphql";
|
||||
// import * as fs from "fs";
|
||||
// import * as path from "path";
|
||||
// import * as typescriptPlugin from "@graphql-codegen/typescript";
|
||||
|
||||
// const __filename = fileURLToPath(import.meta.url);
|
||||
// const __dirname = path.dirname(__filename);
|
||||
|
||||
// const schema: GraphQLSchema = buildSchema(`type A { name: String }`);
|
||||
const outputFile = "gquery.generated.ts";
|
||||
// const config = {
|
||||
// documents: [],
|
||||
// config: {}, // used by a plugin internally, although the 'typescript' plugin currently // returns the string output, rather than writing to a file
|
||||
// filename: outputFile,
|
||||
// schema: parse(printSchema(schema)),
|
||||
// plugins: [
|
||||
// // Each plugin should be an object
|
||||
// {
|
||||
// typescript: {}, // Here you can pass configuration to the plugin
|
||||
// },
|
||||
// ],
|
||||
// pluginMap: {
|
||||
// typescript: typescriptPlugin,
|
||||
// },
|
||||
// };
|
||||
|
||||
const fileRegex = /\.(graphql)$/;
|
||||
const fileRegex = /\.(graphql)$/; // not used, will be for the vite rerun
|
||||
|
||||
export default function levelupViteCodegen(options) {
|
||||
if (!options.schema) {
|
||||
|
|
@ -45,31 +17,32 @@ export default function levelupViteCodegen(options) {
|
|||
const { schema, output, gPath } = options;
|
||||
|
||||
return {
|
||||
name: "levelup-vite-codegen",
|
||||
|
||||
name: "g-query-codegen",
|
||||
async buildStart() {
|
||||
try {
|
||||
const generatedFiles = await generate(
|
||||
await generate(
|
||||
{
|
||||
schema,
|
||||
documents: "./src/**/*.graphql",
|
||||
generates: {
|
||||
[`${process.cwd()}/${output}/gquery-types.generated.ts`]: {
|
||||
// * Generates the types for your schema
|
||||
[`${process.cwd()}/${output}/types.gGenerated.ts`]: {
|
||||
plugins: ["typescript"],
|
||||
},
|
||||
// * Generates near file .ts files for your fetch functions
|
||||
[`${process.cwd()}/${output}`]: {
|
||||
config: {
|
||||
gPath,
|
||||
},
|
||||
preset: "near-operation-file",
|
||||
presetConfig: {
|
||||
extension: ".generated.ts",
|
||||
extension: ".gGenerated.ts",
|
||||
folder: "./",
|
||||
baseTypesPath: `gquery-types.generated.ts`,
|
||||
baseTypesPath: `types.gGenerated.ts`,
|
||||
},
|
||||
plugins: [
|
||||
"typescript-operations",
|
||||
"@leveluptuts/g-query/codegen-plugin",
|
||||
"typescript-operations", // operations, gets you types for operations (queries and mutations)
|
||||
"@leveluptuts/g-query/codegen-plugin", // g-query codegen plugin.
|
||||
],
|
||||
},
|
||||
},
|
||||
|
|
|
|||
63
dist/gFetch.d.ts
vendored
Normal file
63
dist/gFetch.d.ts
vendored
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
import { DefinitionNode, DocumentNode } from "graphql";
|
||||
import type { Readable } from "svelte/store";
|
||||
export declare type GFetchQueryDefault = {
|
||||
errors?: string[];
|
||||
};
|
||||
declare type OptionalPropertyNames<T> = {
|
||||
[K in keyof T]-?: {} extends {
|
||||
[P in K]: T[K];
|
||||
} ? K : never;
|
||||
}[keyof T];
|
||||
declare type SpreadProperties<L, R, K extends keyof L & keyof R> = {
|
||||
[P in K]: L[P] | Exclude<R[P], undefined>;
|
||||
};
|
||||
declare type Id<T> = T extends infer U ? {
|
||||
[K in keyof U]: U[K];
|
||||
} : never;
|
||||
declare type SpreadTwo<L, R> = Id<Pick<L, Exclude<keyof L, keyof R>> & Pick<R, Exclude<keyof R, OptionalPropertyNames<R>>> & Pick<R, Exclude<OptionalPropertyNames<R>, keyof L>> & SpreadProperties<L, R, OptionalPropertyNames<R> & keyof L>>;
|
||||
declare type Spread<A extends readonly [...any]> = A extends [infer L, ...infer R] ? SpreadTwo<L, Spread<R>> : unknown;
|
||||
export declare type GFetchQueryResult<F> = {
|
||||
[k: string]: F;
|
||||
};
|
||||
export declare type GFetchQueries = {
|
||||
query: DocumentNode;
|
||||
variables?: Record<string, unknown>;
|
||||
};
|
||||
export declare function gqlToString(tag: DocumentNode): string;
|
||||
/**
|
||||
* Finds the Name value from the OperationDefinition of a Document
|
||||
*/
|
||||
export declare const getOperationName: (query: DocumentNode) => string | undefined;
|
||||
export declare const stringifyDocument: (node: string | DefinitionNode | DocumentNode) => string;
|
||||
declare type gFetchProperties = {
|
||||
queries: GFetchQueries[];
|
||||
fetch: typeof fetch;
|
||||
};
|
||||
export declare type ApolloClientOptions = {
|
||||
path?: string;
|
||||
};
|
||||
export declare type ApolloClient = {
|
||||
path?: string;
|
||||
};
|
||||
export declare type GFetchReturn<T> = {
|
||||
data: T;
|
||||
errors?: Error;
|
||||
};
|
||||
export declare type GGetParameters<Variables> = {
|
||||
variables?: Variables;
|
||||
fetch: typeof fetch;
|
||||
};
|
||||
export declare type GFetchReturnWithErrors<T> = Spread<[T, GFetchQueryDefault]>;
|
||||
export declare class GFetch extends Object {
|
||||
path: string;
|
||||
constructor(options: ApolloClientOptions);
|
||||
fetch<T>({ queries, fetch, }: gFetchProperties): Promise<GFetchReturnWithErrors<T>>;
|
||||
oFetch<F>({ queries, }: {
|
||||
queries: GFetchQueries[];
|
||||
}): Readable<GFetchReturnWithErrors<F>>;
|
||||
private unsubscribe;
|
||||
private makeSubscribe;
|
||||
private fetchDataForSubscription;
|
||||
}
|
||||
export declare const data: import("svelte/store").Writable<unknown>;
|
||||
export {};
|
||||
42
dist/gFetch.js
vendored
42
dist/gFetch.js
vendored
|
|
@ -1,9 +1,45 @@
|
|||
import { Kind, print, } from "graphql";
|
||||
import { readable, writable } from "svelte/store";
|
||||
import { formatDocument as addTypenameToDocument } from "./utils/format";
|
||||
// This function accepts a graphql document and returns a string to be used
|
||||
// in fetch calls
|
||||
export function gqlToString(tag) {
|
||||
return tag.loc.source.body;
|
||||
}
|
||||
/**
|
||||
* Finds the Name value from the OperationDefinition of a Document
|
||||
*/
|
||||
export const getOperationName = (query) => {
|
||||
for (let i = 0, l = query.definitions.length; i < l; i++) {
|
||||
const node = query.definitions[i];
|
||||
if (node.kind === Kind.OPERATION_DEFINITION && node.name) {
|
||||
return node.name.value;
|
||||
}
|
||||
}
|
||||
};
|
||||
export const stringifyDocument = (node) => {
|
||||
let str = (typeof node !== "string" ? print(node) : node)
|
||||
.replace(/([\s,]|#[^\n\r]+)+/g, " ")
|
||||
.trim();
|
||||
// if (typeof node !== "string") {
|
||||
// const operationName = "definitions" in node && getOperationName(node);
|
||||
// if (operationName) {
|
||||
// str = `# ${operationName}\n${str}`;
|
||||
// }
|
||||
// if (!node.loc) {
|
||||
// (node as WritableLocation).loc = {
|
||||
// start: 0,
|
||||
// end: str.length,
|
||||
// source: {
|
||||
// body: str,
|
||||
// name: "gql",
|
||||
// locationOffset: { line: 1, column: 1 },
|
||||
// },
|
||||
// } as Location;
|
||||
// }
|
||||
// }
|
||||
return str;
|
||||
};
|
||||
export class GFetch extends Object {
|
||||
constructor(options) {
|
||||
super();
|
||||
|
|
@ -20,9 +56,11 @@ export class GFetch extends Object {
|
|||
if (!fetch && window) {
|
||||
fetch = window.fetch;
|
||||
}
|
||||
let document = addTypenameToDocument(queries[0].query);
|
||||
let documentString = stringifyDocument(document);
|
||||
const newQueries = {
|
||||
...queries[0],
|
||||
query: gqlToString(queries[0].query),
|
||||
query: documentString,
|
||||
};
|
||||
// This is generic fetch, that is polyfilled via svelte kit
|
||||
// graph ql fetches must be POST
|
||||
|
|
@ -88,8 +126,6 @@ export class GFetch extends Object {
|
|||
export const data = writable();
|
||||
// ! IDEAS
|
||||
// Mutations should take care of updating a generated writeable.
|
||||
// import { tutorial } from '$graphql/state'
|
||||
// import { updateTutorial } from '$graphql/gfetch.generated'
|
||||
// updateTutorial()
|
||||
// $tutorial is auto updated site wide
|
||||
// Devtools based on svelte toy
|
||||
|
|
|
|||
2
dist/gFetch.js.map
vendored
2
dist/gFetch.js.map
vendored
|
|
@ -1 +1 @@
|
|||
{"version":3,"file":"gF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E,KAAK,EAAE,CAAC,CAAC;YACtD,GAAG,CAAC,QAAQ,CAAC,CAAC;SACf;QAAC,OAAO,KAAK,EAAE;YACd,+CAA+C;YAC/C,yBAAyB;YACzB,IAAI,CAAC,KAAK,GAAG,KAAK,CAAC;YACnB,GAAG,CAAC,IAAI,CAAC,CAAC;SACX;IACH,CAAC;CACF;AAED,MAAM,CAAC,MAAM,IAAI,GAAG,QAAQ,EAAE,CAAC;AAE/B,UAAU;AACV,gEAAgE;AAChE,mBAAmB;AACnB,sCAAsC;AACtC,+BAA+B"}
|
||||
14
dist/index.d.ts
vendored
Normal file
14
dist/index.d.ts
vendored
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
export declare const gCache: {
|
||||
subscribe: (this: void, run: import("svelte/store").Subscriber<{}>, invalidate?: (value?: {}) => void) => import("svelte/store").Unsubscriber;
|
||||
set: (this: void, value: {}) => void;
|
||||
update: (this: void, updater: import("svelte/store").Updater<{}>) => void;
|
||||
hydrate: (newData: any) => Promise<void>;
|
||||
};
|
||||
interface CacheFunctionOptions {
|
||||
update?: boolean;
|
||||
}
|
||||
export declare function gQuery(typename: any, { query, variables }: {
|
||||
query: any;
|
||||
variables: any;
|
||||
}, { update }?: CacheFunctionOptions): Promise<void>;
|
||||
export * from "./gFetch";
|
||||
2
dist/index.js
vendored
2
dist/index.js
vendored
|
|
@ -20,7 +20,7 @@ export const gCache = newGCache();
|
|||
export async function gQuery(typename, { query, variables }, { update } = {}) {
|
||||
const current = get(gCache);
|
||||
// Extremely Naive cache
|
||||
// Just checks to see if the data is there, if it is, don't
|
||||
// Just checks to see if the data is there based on the query, if it is, don't
|
||||
// Hit the network again
|
||||
// if update option is present, then we want to update the cache
|
||||
if (!current?.[typename] || update) {
|
||||
|
|
|
|||
2
dist/index.js.map
vendored
2
dist/index.js.map
vendored
|
|
@ -1 +1 @@
|
|||
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ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AO,CAAC,OAAO;QAC5B,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE;YACb,OAAO;gBACL,GAAG,GAAG;gBACN,GAAG,OAAO;aACX,CAAC;QACJ,CAAC,CAAC,CAAC;IACL,CAAC;IAED,OAAO;QACL,SAAS;QACT,GAAG;QACH,MAAM;QACN,OAAO;KACR,CAAC;AACJ,CAAC,CAAC;AAEF,MAAM,CAAC,MAAM,MAAM,GAAG,SAAS,EAAE,CAAC;AAMlC,MAAM,CAAC,KAAK,UAAU,MAAM,CAC1B,QAAQ,EACR,EAAE,KAAK,EAAE,SAAS,EAAE,EACpB,EAAE,MAAM,KAA2B,EAAE;IAErC,MAAM,OAAO,GAAG,GAAG,CAAC,MAAM,CAAC,CAAC;IAE5B,wBAAwB;IACxB,8EAA8E;IAC9E,wBAAwB;IACxB,gEAAgE;IAChE,IAAI,CAAC,OAAO,EAAE,CAAC,QAAQ,CAAC,IAAI,MAAM,EAAE;QAClC,MAAM,OAAO,GAAG,MAAM,KAAK,CAAC;YAC1B,SAAS;YACT,KAAK;SACN,CAAC,CAAC;QAEH,MAAM,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC;KAC/B;AACH,CAAC;AAED,cAAc,UAAU,CAAC"}
|
||||
3
dist/utils/format.d.ts
vendored
Normal file
3
dist/utils/format.d.ts
vendored
Normal file
|
|
@ -0,0 +1,3 @@
|
|||
import { DocumentNode } from "graphql";
|
||||
export declare const collectTypesFromResponse: (response: object) => string[];
|
||||
export declare const formatDocument: <T extends DocumentNode>(node: T) => T;
|
||||
51
dist/utils/format.js
vendored
Normal file
51
dist/utils/format.js
vendored
Normal file
|
|
@ -0,0 +1,51 @@
|
|||
import { Kind, visit, } from "graphql";
|
||||
const collectTypes = (obj, types) => {
|
||||
if (Array.isArray(obj)) {
|
||||
for (let i = 0; i < obj.length; i++)
|
||||
collectTypes(obj[i], types);
|
||||
}
|
||||
else if (typeof obj === "object" && obj !== null) {
|
||||
for (const key in obj) {
|
||||
if (key === "__typename" && typeof obj[key] === "string") {
|
||||
types[obj[key]] = 0;
|
||||
}
|
||||
else {
|
||||
collectTypes(obj[key], types);
|
||||
}
|
||||
}
|
||||
}
|
||||
return types;
|
||||
};
|
||||
export const collectTypesFromResponse = (response) => Object.keys(collectTypes(response, {}));
|
||||
const formatNode = (node) => {
|
||||
if (node.selectionSet &&
|
||||
!node.selectionSet.selections.some((node) => node.kind === Kind.FIELD &&
|
||||
node.name.value === "__typename" &&
|
||||
!node.alias)) {
|
||||
let formattedNode = {
|
||||
...node,
|
||||
selectionSet: {
|
||||
...node.selectionSet,
|
||||
selections: [
|
||||
...node.selectionSet.selections,
|
||||
{
|
||||
kind: Kind.FIELD,
|
||||
name: {
|
||||
kind: Kind.NAME,
|
||||
value: "__typename",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
return formattedNode;
|
||||
}
|
||||
};
|
||||
export const formatDocument = (node) => {
|
||||
let result = visit(node, {
|
||||
Field: formatNode,
|
||||
InlineFragment: formatNode,
|
||||
});
|
||||
return result;
|
||||
};
|
||||
//# sourceMappingURL=format.js.map
|
||||
1
dist/utils/format.js.map
vendored
Normal file
1
dist/utils/format.js.map
vendored
Normal file
|
|
@ -0,0 +1 @@
|
|||
{"version":3,"file":"format.js","sourceRoot":"","sources":["../../src/utils/format.ts"],"names":[],"mappings":"AAAA,OAAO,EAKL,IAAI,EACJ,KAAK,GACN,MAAM,SAAS,CAAC;AAOjB,MAAM,YAAY,GAAG,CACnB,GAA8B,EAC9B,KAAsC,EACtC,EAAE;IACF,IAAI,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,EAAE;QACtB,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,GAAG,CAAC,MAAM,EAAE,CAAC,EAAE;YAAE,YAAY,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,KAAK,CAAC,CAAC;KAClE;SAAM,IAAI,OAAO,GAAG,KAAK,QAAQ,IAAI,GAAG,KAAK,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K,CAAC,IAAI,EAAE;QACvB,KAAK,EAAE,UAAU;QACjB,cAAc,EAAE,UAAU;KAC3B,CAAC,CAAC;IACH,OAAO,MAAsB,CAAC;AAChC,CAAC,CAAC"}
|
||||
14
package.json
14
package.json
|
|
@ -4,8 +4,6 @@
|
|||
"url": "https://github.com/leveluptuts/gQuery/issues"
|
||||
},
|
||||
"dependencies": {
|
||||
"@graphql-codegen/cli": "^2.2.1",
|
||||
"@graphql-codegen/typescript-operations": "^2.1.8",
|
||||
"camel-case": "^4.1.2",
|
||||
"pascal-case": "^3.1.2",
|
||||
"svelte": "^3.44.0",
|
||||
|
|
@ -13,18 +11,23 @@
|
|||
},
|
||||
"description": "Not like jQuery. A GraphQL Fetcher & Cache for Svelte Kit",
|
||||
"devDependencies": {
|
||||
"@babel/types": "^7.15.6",
|
||||
"@graphql-codegen/cli": "^2.2.1",
|
||||
"@graphql-codegen/import-types-preset": "^2.1.6",
|
||||
"@graphql-codegen/near-operation-file-preset": "^2.1.6",
|
||||
"@graphql-codegen/plugin-helpers": "^2.2.0",
|
||||
"@graphql-codegen/typescript-operations": "^2.1.8",
|
||||
"@graphql-codegen/visitor-plugin-common": "^2.4.0",
|
||||
"@urql/core": "^2.3.3",
|
||||
"graphql": "^15.6.1",
|
||||
"just-pascal-case": "^2.0.0",
|
||||
"typescript": "^4.4.4"
|
||||
},
|
||||
"exports": {
|
||||
".": "./dist/index.js",
|
||||
"./*": "./dist/index.js",
|
||||
"./codegen": "./codegen/dist/plugin.js",
|
||||
"./codegen-plugin": "./codegen/dist/codegen.js",
|
||||
"./codegen": "./codegen/plugin.js",
|
||||
"./codegen-plugin": "./codegen/codegen.js",
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"homepage": "https://github.com/leveluptuts/gQuery#readme",
|
||||
|
|
@ -43,5 +46,6 @@
|
|||
"test": "echo \"Error: no test specified\" && exit 1"
|
||||
},
|
||||
"type": "module",
|
||||
"version": "0.0.4"
|
||||
"types": "./dist/index.d.ts",
|
||||
"version": "0.0.5"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,14 @@
|
|||
import type { DocumentNode } from "graphql/language/ast";
|
||||
import {
|
||||
Location,
|
||||
DefinitionNode,
|
||||
DocumentNode,
|
||||
Kind,
|
||||
parse,
|
||||
print,
|
||||
} from "graphql";
|
||||
import { readable, writable } from "svelte/store";
|
||||
import type { Readable } from "svelte/store";
|
||||
import { formatDocument as addTypenameToDocument } from "./utils/format";
|
||||
|
||||
// What's the deal with *gFetch*?
|
||||
// gFetch is a 0 dependency fetcher for graphql that accepts a custom fetch function
|
||||
|
|
@ -56,6 +64,51 @@ export function gqlToString(tag: DocumentNode): string {
|
|||
return tag.loc.source.body;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the Name value from the OperationDefinition of a Document
|
||||
*/
|
||||
export const getOperationName = (query: DocumentNode): string | undefined => {
|
||||
for (let i = 0, l = query.definitions.length; i < l; i++) {
|
||||
const node = query.definitions[i];
|
||||
if (node.kind === Kind.OPERATION_DEFINITION && node.name) {
|
||||
return node.name.value;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
interface WritableLocation {
|
||||
loc: Location | undefined;
|
||||
}
|
||||
|
||||
export const stringifyDocument = (
|
||||
node: string | DefinitionNode | DocumentNode
|
||||
): string => {
|
||||
let str = (typeof node !== "string" ? print(node) : node)
|
||||
.replace(/([\s,]|#[^\n\r]+)+/g, " ")
|
||||
.trim();
|
||||
|
||||
// if (typeof node !== "string") {
|
||||
// const operationName = "definitions" in node && getOperationName(node);
|
||||
// if (operationName) {
|
||||
// str = `# ${operationName}\n${str}`;
|
||||
// }
|
||||
|
||||
// if (!node.loc) {
|
||||
// (node as WritableLocation).loc = {
|
||||
// start: 0,
|
||||
// end: str.length,
|
||||
// source: {
|
||||
// body: str,
|
||||
// name: "gql",
|
||||
// locationOffset: { line: 1, column: 1 },
|
||||
// },
|
||||
// } as Location;
|
||||
// }
|
||||
// }
|
||||
|
||||
return str;
|
||||
};
|
||||
|
||||
type gFetchProperties = {
|
||||
queries: GFetchQueries[];
|
||||
fetch: typeof fetch;
|
||||
|
|
@ -73,6 +126,11 @@ export type GFetchReturn<T> = {
|
|||
errors?: Error;
|
||||
};
|
||||
|
||||
export type GGetParameters<Variables> = {
|
||||
variables?: Variables;
|
||||
fetch: typeof fetch;
|
||||
};
|
||||
|
||||
export type GFetchReturnWithErrors<T> = Spread<[T, GFetchQueryDefault]>;
|
||||
|
||||
export class GFetch extends Object {
|
||||
|
|
@ -97,9 +155,11 @@ export class GFetch extends Object {
|
|||
if (!fetch && window) {
|
||||
fetch = window.fetch;
|
||||
}
|
||||
let document: DocumentNode = addTypenameToDocument(queries[0].query);
|
||||
let documentString: string = stringifyDocument(document);
|
||||
const newQueries = {
|
||||
...queries[0],
|
||||
query: gqlToString(queries[0].query),
|
||||
query: documentString,
|
||||
};
|
||||
|
||||
// This is generic fetch, that is polyfilled via svelte kit
|
||||
|
|
@ -178,8 +238,6 @@ export const data = writable();
|
|||
|
||||
// ! IDEAS
|
||||
// Mutations should take care of updating a generated writeable.
|
||||
// import { tutorial } from '$graphql/state'
|
||||
// import { updateTutorial } from '$graphql/gfetch.generated'
|
||||
// updateTutorial()
|
||||
// $tutorial is auto updated site wide
|
||||
// Devtools based on svelte toy
|
||||
|
|
|
|||
|
|
@ -34,7 +34,7 @@ export async function gQuery(
|
|||
const current = get(gCache);
|
||||
|
||||
// Extremely Naive cache
|
||||
// Just checks to see if the data is there, if it is, don't
|
||||
// Just checks to see if the data is there based on the query, if it is, don't
|
||||
// Hit the network again
|
||||
// if update option is present, then we want to update the cache
|
||||
if (!current?.[typename] || update) {
|
||||
|
|
|
|||
73
src/utils/format.ts
Normal file
73
src/utils/format.ts
Normal file
|
|
@ -0,0 +1,73 @@
|
|||
import {
|
||||
DocumentNode,
|
||||
FieldNode,
|
||||
InlineFragmentNode,
|
||||
SelectionNode,
|
||||
Kind,
|
||||
visit,
|
||||
} from "graphql";
|
||||
|
||||
interface EntityLike {
|
||||
[key: string]: EntityLike | EntityLike[] | any;
|
||||
__typename: string | null | void;
|
||||
}
|
||||
|
||||
const collectTypes = (
|
||||
obj: EntityLike | EntityLike[],
|
||||
types: { [typename: string]: unknown }
|
||||
) => {
|
||||
if (Array.isArray(obj)) {
|
||||
for (let i = 0; i < obj.length; i++) collectTypes(obj[i], types);
|
||||
} else if (typeof obj === "object" && obj !== null) {
|
||||
for (const key in obj) {
|
||||
if (key === "__typename" && typeof obj[key] === "string") {
|
||||
types[obj[key] as string] = 0;
|
||||
} else {
|
||||
collectTypes(obj[key], types);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return types;
|
||||
};
|
||||
|
||||
export const collectTypesFromResponse = (response: object) =>
|
||||
Object.keys(collectTypes(response as EntityLike, {}));
|
||||
|
||||
const formatNode = (node: FieldNode | InlineFragmentNode) => {
|
||||
if (
|
||||
node.selectionSet &&
|
||||
!node.selectionSet.selections.some(
|
||||
(node) =>
|
||||
node.kind === Kind.FIELD &&
|
||||
node.name.value === "__typename" &&
|
||||
!node.alias
|
||||
)
|
||||
) {
|
||||
let formattedNode = {
|
||||
...node,
|
||||
selectionSet: {
|
||||
...node.selectionSet,
|
||||
selections: [
|
||||
...(node.selectionSet.selections as SelectionNode[]),
|
||||
{
|
||||
kind: Kind.FIELD,
|
||||
name: {
|
||||
kind: Kind.NAME,
|
||||
value: "__typename",
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
return formattedNode;
|
||||
}
|
||||
};
|
||||
|
||||
export const formatDocument = <T extends DocumentNode>(node: T): T => {
|
||||
let result = visit(node, {
|
||||
Field: formatNode,
|
||||
InlineFragment: formatNode,
|
||||
});
|
||||
return result as unknown as T;
|
||||
};
|
||||
|
|
@ -4,6 +4,7 @@
|
|||
"module": "es2020",
|
||||
"lib": ["es2020", "DOM"],
|
||||
"outDir": "./dist",
|
||||
"declaration": true,
|
||||
"target": "es2020",
|
||||
"importsNotUsedAsValues": "error",
|
||||
"isolatedModules": true,
|
||||
|
|
|
|||
Loading…
Reference in a new issue