diff --git a/README.md b/README.md index 2037872..6c715a5 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ This also gives us a `get` function for queries based on the query name. ie `get // Cache becomes populated with data available for SSR import { user } from './UserQueries.gGenerated.graphql' - // $: console.log($user) //data available for ssr + // $: console.log($user.user) //data available for ssr ``` @@ -89,9 +89,9 @@ It's a Svelte Writable Store. So after a mutation you can quickly and easily man ```javascript import { user, someMutation } from "./UserQueries.gGenerated.graphql"; -$user = null; // clears the cache +$user.user = null; // clears the cache -$user = await someMutation({ variables }); // if this returns the correct data +$user.user = await someMutation({ variables }); // if this returns the correct data ``` ### Q? Can't you update the cache magically for me after a mutation? diff --git a/codegen/codegen.js b/codegen/codegen.js index fbd9152..a95fc23 100644 --- a/codegen/codegen.js +++ b/codegen/codegen.js @@ -1,8 +1,9 @@ import { visit, concatAST, Kind, } from "graphql"; import "@graphql-codegen/plugin-helpers"; -import { ClientSideBaseVisitor } from "@graphql-codegen/visitor-plugin-common"; +import { ClientSideBaseVisitor, } from "@graphql-codegen/visitor-plugin-common"; import pascalCase from "just-pascal-case"; export const plugin = (schema, documents, config) => { + console.log("🛠️ Codegen Starting"); const allAst = concatAST(documents.map((d) => d.document)); const allFragments = [ ...allAst.definitions.filter((d) => d.kind === Kind.FRAGMENT_DEFINITION).map((fragmentDef) => ({ @@ -13,7 +14,7 @@ export const plugin = (schema, documents, config) => { })), ...(config.externalFragments || []), ]; - const visitor = new ClientSideBaseVisitor(schema, allFragments, {}, { documentVariableSuffix: "Doc" }, documents); + const visitor = new ClientSideBaseVisitor(schema, allFragments, config, { documentVariableSuffix: "Doc" }, documents); const visitorResult = visit(allAst, { leave: visitor }); const operations = allAst.definitions.filter((d) => d.kind === Kind.OPERATION_DEFINITION); const defaultTypes = ` @@ -27,6 +28,7 @@ type SubscribeWrapperArgs = { variables?: T, } + interface CacheFunctionOptions { update?: boolean } @@ -35,20 +37,18 @@ interface CacheFunctionOptions { const ops = operations .map((o) => { var _a; - console.log("o", o.selectionSet.selections); if (o) { + console.log("o", 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} = writable<${op}>() -export const ${name} = ({ variables, fetch}: FetchWrapperArgs<${opv}>): +export const fetch${pascalName} = ({ variables, fetch}: FetchWrapperArgs<${opv}>): Promise> => g.fetch<${op}>({ queries: [{ query: ${pascalName}Doc, variables }], @@ -56,29 +56,17 @@ export const ${name} = ({ variables, fetch}: FetchWrapperArgs<${opv}>): }) - // Cached - export async function get${pascalCase(name)}({ fetch, variables }: GGetParameters<${opv}>, options?: CacheFunctionOptions) { +// Cached +export async function get${pascalName}({ 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) + await ${name}.set({ ...data, error: data?.error, gQueryStatus: 'LOADED' }) + return data } `; - // If config is set to have subscription query, also write the - if (config.subscriptionQuery) { - operations += ` -export const ${name}Subscribe = ({ variables }: SubscribeWrapperArgs<${opv}>): -Readable> => - g.oFetch<${op}>({ - queries: [{ query: ${pascalName}Doc, variables }] - }) - `; - } } else if (o.operation === "mutation") { operations += ` @@ -95,41 +83,13 @@ Promise> => }) .join("\n"); const imports = [ - `import type { Readable } from "svelte/store"`, `import { writable } from "svelte/store"`, + `import type { Writable } from "svelte/store"`, `import { g } from '${config.gPath}'`, `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, + prepend: [...imports, ...visitor.getImports()], content: [ defaultTypes, visitor.fragments, @@ -138,4 +98,7 @@ Promise> => ].join("\n"), }; }; +// TODO +// - add option to force update of cache. ie getUserTutorials({update: true}) +// if update.true is not set, then it will only update if the cache is empty //# sourceMappingURL=codegen.js.map \ No newline at end of file diff --git a/codegen/codegen.js.map b/codegen/codegen.js.map index b7d579d..c121709 100644 --- a/codegen/codegen.js.map +++ b/codegen/codegen.js.map @@ -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,EAAE,qBAAqB,EAAE,MAAM,wCAAwC,CAAC;AAC/E,OAAO,UAAU,MAAM,kBAAkB,CAAC;AAE1C,MAAM,CAAC,MAAM,MAAM,GAAwB,CACzC,MAAqB,EACrB,SAA+B,EAC/B,MAAM,EACN,EAAE;IACF,MAAM,MAAM,GAAG,SAAS,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,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K,OAAO,EAAE;gBAC3B,UAAU,IAAI;eACT,IAAI,eAAe,EAAE;;oBAEhB,UAAU,6CAA6C,GAAG;kCAC5C,EAAE;YACxB,EAAE;wBACU,UAAU;;;;;;2BAMP,UAAU,yCAAyC,GAAG;8BACnD,EAAE;uBACT,UAAU;;;SAGxB,IAAI;;;;CAIZ,CAAC;aACO;iBAAM,IAAI,CAAC,CAAC,SAAS,KAAK,UAAU,EAAE;gBACrC,UAAU,IAAI;eACT,IAAI,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,yCAAyC;QACzC,8CAA8C;QAC9C,sBAAsB,MAAM,CAAC,KAAK,GAAG;QACrC,oFAAoF;KACrF,CAAC;IAEF,OAAO;QACL,OAAO,EAAE,CAAC,GAAG,OAAO,EAAE,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC;QAC9C,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;AACF,OAAO;AACP,6EAA6E;AAC7E,4EAA4E"} \ No newline at end of file diff --git a/codegen/codegen.ts b/codegen/codegen.ts index 1adccdf..01e9ca5 100644 --- a/codegen/codegen.ts +++ b/codegen/codegen.ts @@ -7,7 +7,10 @@ import { OperationDefinitionNode, } from "graphql"; import { Types, PluginFunction } from "@graphql-codegen/plugin-helpers"; -import { ClientSideBaseVisitor } from "@graphql-codegen/visitor-plugin-common"; +import { + ClientSideBaseVisitor, + LoadedFragment, +} from "@graphql-codegen/visitor-plugin-common"; import pascalCase from "just-pascal-case"; export const plugin: PluginFunction = ( @@ -15,9 +18,11 @@ export const plugin: PluginFunction = ( documents: Types.DocumentFile[], config ) => { + console.log("🛠️ Codegen Starting"); + const allAst = concatAST(documents.map((d) => d.document)); - const allFragments = [ + const allFragments: LoadedFragment[] = [ ...( allAst.definitions.filter( (d) => d.kind === Kind.FRAGMENT_DEFINITION @@ -34,7 +39,7 @@ export const plugin: PluginFunction = ( const visitor = new ClientSideBaseVisitor( schema, allFragments, - {}, + config, { documentVariableSuffix: "Doc" }, documents ); @@ -55,6 +60,7 @@ type SubscribeWrapperArgs = { variables?: T, } + interface CacheFunctionOptions { update?: boolean } @@ -64,9 +70,8 @@ interface CacheFunctionOptions { const ops = operations .map((o) => { if (o) { + console.log("o", o); const name = o?.name?.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`; @@ -74,9 +79,9 @@ interface CacheFunctionOptions { if (o.operation === "query") { operations += ` -export const ${name}Store = writable() +export const ${name} = writable<${op}>() -export const ${name} = ({ variables, fetch}: FetchWrapperArgs<${opv}>): +export const fetch${pascalName} = ({ variables, fetch}: FetchWrapperArgs<${opv}>): Promise> => g.fetch<${op}>({ queries: [{ query: ${pascalName}Doc, variables }], @@ -85,28 +90,16 @@ export const ${name} = ({ variables, fetch}: FetchWrapperArgs<${opv}>): // Cached -export async function get${pascalCase( - name - )}({ fetch, variables }: GGetParameters<${opv}>, options?: CacheFunctionOptions) { +export async function get${pascalName}({ 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) + await ${name}.set({ ...data, error: data?.error, gQueryStatus: 'LOADED' }) + return data } `; - // If config is set to have subscription query, also write the - if (config.subscriptionQuery) { - operations += ` -export const ${name}Subscribe = ({ variables }: SubscribeWrapperArgs<${opv}>): -Readable> => - g.oFetch<${op}>({ - queries: [{ query: ${pascalName}Doc, variables }] - }) - `; - } } else if (o.operation === "mutation") { operations += ` export const ${name} = ({ variables }: SubscribeWrapperArgs<${opv}>): @@ -124,16 +117,14 @@ Promise> => .join("\n"); const imports = [ - `import type { Readable } from "svelte/store"`, `import { writable } from "svelte/store"`, + `import type { Writable } from "svelte/store"`, `import { g } from '${config.gPath}'`, `import type { GFetchReturnWithErrors, GGetParameters } from '@leveluptuts/g-query'`, - `import { gQuery } from '@leveluptuts/g-query'`, - `import gql from "graphql-tag"`, ]; return { - prepend: imports, + prepend: [...imports, ...visitor.getImports()], content: [ defaultTypes, visitor.fragments, @@ -142,3 +133,6 @@ Promise> => ].join("\n"), }; }; +// TODO +// - add option to force update of cache. ie getUserTutorials({update: true}) +// if update.true is not set, then it will only update if the cache is empty diff --git a/codegen/plugin.js b/codegen/plugin.js index 2c17218..d4fa73e 100644 --- a/codegen/plugin.js +++ b/codegen/plugin.js @@ -1,6 +1,5 @@ import { generate } from "@graphql-codegen/cli"; -const outputFile = "gquery.generated.ts"; -const fileRegex = /\.(graphql)$/; +const fileRegex = /\.(graphql)$/; // not used, will be for the vite rerun export default function levelupViteCodegen(options) { if (!options.schema) { throw new Error("No schema provided"); @@ -12,30 +11,39 @@ export default function levelupViteCodegen(options) { throw new Error("No gPath directory specified. gPath is where you've initialized the 'g' client"); } const { schema, output, gPath } = options; + console.log("running plugin"); return { - name: "levelup-vite-codegen", + name: "g-query-codegen", async buildStart() { try { - const generatedFiles = await generate({ + // *1. Remove all .gGenerated files + // TODO: Find and remove all .gGenerated files + // *2. 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: { + useTypeImports: true, gPath, + importDocumentNodeExternallyFrom: "near-operation-file", + inlineFragmentTypes: "combine", }, 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", + "@leveluptuts/g-query/codegen-plugin", // g-query codegen plugin. ], }, }, diff --git a/codegen/plugin.js.map b/codegen/plugin.js.map index 38615d8..dcadc06 100644 --- a/codegen/plugin.js.map +++ b/codegen/plugin.js.map @@ -1 +1 @@ -{"version":3,"file":"plugin.js","sourceRoot":"","sources":["plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,MAAM,UAAU,GAAG,qBAAqB,CAAC;AACzC,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,CACb,gFAAgF,CACjF,CAAC;KACH;IAED,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,KAAK,EAAE,GAAG,OAAO,CAAC;IAE1C,OAAO;QACL,IAAI,EAAE,sBAAsB;QAE5B,KAAK,CAAC,UAAU;YACd,IAAI;gBACF,MAAM,cAAc,GAAG,MAAM,QAAQ,CACnC;oBACE,MAAM;oBACN,SAAS,EAAE,oBAAoB;oBAC/B,SAAS,EAAE;wBACT,CAAC,GAAG,OAAO,CAAC,GAAG,EAAE,IAAI,MAAM,4BAA4B,CAAC,EAAE;4BACxD,OAAO,EAAE,CAAC,YAAY,CAAC;yBACxB;wBACD,CAAC,GAAG,OAAO,CAAC,GAAG,EAAE,IAAI,MAAM,EAAE,CAAC,EAAE;4BAC9B,MAAM,EAAE;gCACN,KAAK;6BACN;4BACD,MAAM,EAAE,qBAAqB;4BAC7B,YAAY,EAAE;gCACZ,SAAS,EAAE,eAAe;gCAC1B,MAAM,EAAE,IAAI;gCACZ,aAAa,EAAE,2BAA2B;6BAC3C;4BACD,OAAO,EAAE;gCACP,uBAAuB;gCACvB,qCAAqC;6BACtC;yBACF;qBACF;iBACF,EACD,IAAI,CACL,CAAC;aACH;YAAC,OAAO,CAAC,EAAE;gBACV,OAAO,CAAC,GAAG,CAAC,+CAA+C,CAAC,CAAC;gBAC7D,OAAO,CAAC,GAAG,CACT,0FAA0F,CAC3F,CAAC;gBACF,OAAO,CAAC,GAAG,CACT,uFAAuF,CACxF,CAAC;aACH;YACD,OAAO;QACT,CAAC;QAED,SAAS,CAAC,GAAG,EAAE,EAAE,IAAG,CAAC;KACtB,CAAC;AACJ,CAAC"} \ No newline at end of file +{"version":3,"file":"plugin.js","sourceRoot":"","sources":["plugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,MAAM,SAAS,GAAG,cAAc,CAAC,CAAC,uCAAuC;AAEzE,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,CACb,gFAAgF,CACjF,CAAC;KAC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ts b/codegen/plugin.ts index d1773f6..41afbd4 100644 --- a/codegen/plugin.ts +++ b/codegen/plugin.ts @@ -16,10 +16,15 @@ export default function levelupViteCodegen(options) { const { schema, output, gPath } = options; + console.log("running plugin"); return { name: "g-query-codegen", async buildStart() { try { + // *1. Remove all .gGenerated files + // TODO: Find and remove all .gGenerated files + // *2. Generate + await generate( { schema, @@ -32,7 +37,10 @@ export default function levelupViteCodegen(options) { // * Generates near file .ts files for your fetch functions [`${process.cwd()}/${output}`]: { config: { + useTypeImports: true, gPath, + importDocumentNodeExternallyFrom: "near-operation-file", + inlineFragmentTypes: "combine", }, preset: "near-operation-file", presetConfig: { diff --git a/dist/gFetch.d.ts b/dist/gFetch.d.ts index 712ee97..6ecf88a 100644 --- a/dist/gFetch.d.ts +++ b/dist/gFetch.d.ts @@ -1,5 +1,4 @@ import { DefinitionNode, DocumentNode } from "graphql"; -import type { Readable } from "svelte/store"; export declare type GFetchQueryDefault = { errors?: string[]; }; @@ -51,13 +50,6 @@ export declare type GFetchReturnWithErrors = Spread<[T, GFetchQueryDefault]>; export declare class GFetch extends Object { path: string; constructor(options: ApolloClientOptions); - fetch({ queries, fetch, }: gFetchProperties): Promise>; - oFetch({ queries, }: { - queries: GFetchQueries[]; - }): Readable>; - private unsubscribe; - private makeSubscribe; - private fetchDataForSubscription; + fetch({ queries, fetch, }?: gFetchProperties | {}): Promise>; } -export declare const data: import("svelte/store").Writable; export {}; diff --git a/dist/gFetch.js b/dist/gFetch.js index 95da2ec..147018b 100644 --- a/dist/gFetch.js +++ b/dist/gFetch.js @@ -1,5 +1,5 @@ import { Kind, print, } from "graphql"; -import { readable, writable } from "svelte/store"; +import "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 @@ -21,23 +21,6 @@ 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 { @@ -46,16 +29,10 @@ export class GFetch extends Object { const { path } = options; this.path = path; this.fetch = this.fetch.bind(this); - this.oFetch = this.oFetch.bind(this); } // * gFetch // This is a fetcher that returns a promise that resolves to a graphql response - async fetch({ queries, fetch, }) { - // Get all the queries and transform the docs into strings - // Fetching gql require them to be strings. - if (!fetch && window) { - fetch = window.fetch; - } + async fetch({ queries, fetch, } = {}) { let document = addTypenameToDocument(queries[0].query); let documentString = stringifyDocument(document); const newQueries = { @@ -77,56 +54,58 @@ export class GFetch extends Object { ...data.data, }; } - // * ogFetch - // This function is a fetcher that returns a svelte readable subscription - // This is to be used for client side fetching of data - oFetch({ queries, }) { - // 1. Build the store and initialize it as empty and error free - const initial = new Map(); - // Creates a store that will be used to subscribe to the data - const store = readable(initial, this.makeSubscribe(initial, queries)); - return store; - } - // A dummy function that is used to make subscribe happy. - unsubscribe() { - // Nothing to do in this case - } - // Part of ogFetch - // Designed this way to work will with Svelte's readable store - makeSubscribe(data, queries) { - // Create a closure with access to the - // initial data and initialization arguments - return (set) => { - // 3. This won't get executed until the store has - // its first subscriber. Kick off retrieval. - this.fetchDataForSubscription(data, set, queries); - // We're not waiting for the response. - // Return the unsubscribe function which doesn't do - // do anything here (but is part of the stores protocol). - return this.unsubscribe; - }; - } - // Part of ogFetch - // Runs gFetch and updates subscription - async fetchDataForSubscription(data, set, queries) { - try { - // Dispatch the request for the users - // This code is ONLY run client side, so fetch comes globally from the browser - const response = await this.fetch({ queries, fetch }); - set(response); - } - catch (error) { - // 6b. if there is a fetch error - deal with it - // and let observers know - data.error = error; - set(data); - } - } } -export const data = writable(); +// * ogFetch +// This function is a fetcher that returns a svelte readable subscription +// This is to be used for client side fetching of data +// public oFetch({ +// queries, +// }: { +// queries: GFetchQueries[]; +// }): Readable> { +// // 1. Build the store and initialize it as empty and error free +// const initial = new Map(); +// // Creates a store that will be used to subscribe to the data +// const store = readable(initial, this.makeSubscribe(initial, queries)); +// return store as unknown as Readable>; +// } +// // A dummy function that is used to make subscribe happy. +// private unsubscribe() { +// // Nothing to do in this case +// } +// // Part of ogFetch +// // Designed this way to work will with Svelte's readable store +// private makeSubscribe(data, queries) { +// // Create a closure with access to the +// // initial data and initialization arguments +// return (set) => { +// // 3. This won't get executed until the store has +// // its first subscriber. Kick off retrieval. +// this.fetchDataForSubscription(data, set, queries); +// // We're not waiting for the response. +// // Return the unsubscribe function which doesn't do +// // do anything here (but is part of the stores protocol). +// return this.unsubscribe; +// }; +// } +// // Part of ogFetch +// // Runs gFetch and updates subscription +// private async fetchDataForSubscription(data, set, queries: GFetchQueries[]) { +// try { +// // Dispatch the request for the users +// // This code is ONLY run client side, so fetch comes globally from the browser +// const response = await this.fetch({ queries, fetch }); +// set(response); +// } catch (error) { +// // 6b. if there is a fetch error - deal with it +// // and let observers know +// data.error = error; +// set(data); +// } +// } +// } +// export const data = writable(); // ! IDEAS // Mutations should take care of updating a generated writeable. -// updateTutorial() // $tutorial is auto updated site wide -// Devtools based on svelte toy //# sourceMappingURL=gFetch.js.map \ No newline at end of file diff --git a/dist/gFetch.js.map b/dist/gFetch.js.map index 8283727..a2217ab 100644 --- a/dist/gFetch.js.map +++ b/dist/gFetch.js.map @@ -1 +1 @@ -{"version":3,"file":"gFetch.js","sourceRoot":"","sources":["../src/gFetch.ts"],"names":[],"mappings":"AAAA,OAAO,EAIL,IAAI,EAEJ,KAAK,GACN,MAAM,SAAS,CAAC;AACjB,OAAO,EAAE,QAAQ,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAElD,OAAO,EAAE,cAAc,IAAI,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;AAkDzE,2EAA2E;AAC3E,iBAAiB;AACjB,M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uBAAuB;AACvB,4CAA4C;AAC5C,kFAAkF;AAClF,YAAY;AACZ,8CAA8C;AAC9C,uFAAuF;AACvF,+DAA+D;AAC/D,uBAAuB;AACvB,wBAAwB;AACxB,wDAAwD;AACxD,kCAAkC;AAClC,4BAA4B;AAC5B,mBAAmB;AACnB,QAAQ;AACR,MAAM;AACN,IAAI;AAEJ,kCAAkC;AAElC,UAAU;AACV,gEAAgE;AAChE,sCAAsC"} \ No newline at end of file diff --git a/package.json b/package.json index b38e58e..0fb486b 100644 --- a/package.json +++ b/package.json @@ -47,5 +47,5 @@ }, "type": "module", "types": "./dist/index.d.ts", - "version": "0.0.5" + "version": "0.0.6" } diff --git a/src/gFetch.ts b/src/gFetch.ts index 05d0ede..2ba7bbf 100644 --- a/src/gFetch.ts +++ b/src/gFetch.ts @@ -86,26 +86,6 @@ export const stringifyDocument = ( 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; }; @@ -141,7 +121,6 @@ export class GFetch extends Object { const { path } = options; this.path = path; this.fetch = this.fetch.bind(this); - this.oFetch = this.oFetch.bind(this); } // * gFetch @@ -149,12 +128,7 @@ export class GFetch extends Object { public async fetch({ queries, fetch, - }: gFetchProperties): Promise> { - // Get all the queries and transform the docs into strings - // Fetching gql require them to be strings. - if (!fetch && window) { - fetch = window.fetch; - } + }: gFetchProperties | {} = {}): Promise> { let document: DocumentNode = addTypenameToDocument(queries[0].query); let documentString: string = stringifyDocument(document); const newQueries = { @@ -179,65 +153,64 @@ export class GFetch extends Object { ...data.data, } as GFetchReturnWithErrors; } - - // * ogFetch - // This function is a fetcher that returns a svelte readable subscription - // This is to be used for client side fetching of data - public oFetch({ - queries, - }: { - queries: GFetchQueries[]; - }): Readable> { - // 1. Build the store and initialize it as empty and error free - const initial = new Map(); - // Creates a store that will be used to subscribe to the data - const store = readable(initial, this.makeSubscribe(initial, queries)); - return store as unknown as Readable>; - } - - // A dummy function that is used to make subscribe happy. - private unsubscribe() { - // Nothing to do in this case - } - - // Part of ogFetch - // Designed this way to work will with Svelte's readable store - private makeSubscribe(data, queries) { - // Create a closure with access to the - // initial data and initialization arguments - return (set) => { - // 3. This won't get executed until the store has - // its first subscriber. Kick off retrieval. - this.fetchDataForSubscription(data, set, queries); - - // We're not waiting for the response. - // Return the unsubscribe function which doesn't do - // do anything here (but is part of the stores protocol). - return this.unsubscribe; - }; - } - - // Part of ogFetch - // Runs gFetch and updates subscription - private async fetchDataForSubscription(data, set, queries: GFetchQueries[]) { - try { - // Dispatch the request for the users - // This code is ONLY run client side, so fetch comes globally from the browser - const response = await this.fetch({ queries, fetch }); - set(response); - } catch (error) { - // 6b. if there is a fetch error - deal with it - // and let observers know - data.error = error; - set(data); - } - } } -export const data = writable(); +// * ogFetch +// This function is a fetcher that returns a svelte readable subscription +// This is to be used for client side fetching of data +// public oFetch({ +// queries, +// }: { +// queries: GFetchQueries[]; +// }): Readable> { +// // 1. Build the store and initialize it as empty and error free +// const initial = new Map(); +// // Creates a store that will be used to subscribe to the data +// const store = readable(initial, this.makeSubscribe(initial, queries)); +// return store as unknown as Readable>; +// } + +// // A dummy function that is used to make subscribe happy. +// private unsubscribe() { +// // Nothing to do in this case +// } + +// // Part of ogFetch +// // Designed this way to work will with Svelte's readable store +// private makeSubscribe(data, queries) { +// // Create a closure with access to the +// // initial data and initialization arguments +// return (set) => { +// // 3. This won't get executed until the store has +// // its first subscriber. Kick off retrieval. +// this.fetchDataForSubscription(data, set, queries); + +// // We're not waiting for the response. +// // Return the unsubscribe function which doesn't do +// // do anything here (but is part of the stores protocol). +// return this.unsubscribe; +// }; +// } + +// // Part of ogFetch +// // Runs gFetch and updates subscription +// private async fetchDataForSubscription(data, set, queries: GFetchQueries[]) { +// try { +// // Dispatch the request for the users +// // This code is ONLY run client side, so fetch comes globally from the browser +// const response = await this.fetch({ queries, fetch }); +// set(response); +// } catch (error) { +// // 6b. if there is a fetch error - deal with it +// // and let observers know +// data.error = error; +// set(data); +// } +// } +// } + +// export const data = writable(); // ! IDEAS // Mutations should take care of updating a generated writeable. -// updateTutorial() // $tutorial is auto updated site wide -// Devtools based on svelte toy