@gqty/cli
Version:
## Visit [https://gqty.dev/docs/cli/codegen](https://gqty.dev/docs/cli/codegen)
5 lines (4 loc) • 2.75 kB
JavaScript
import{existsSync as j,promises as C}from"fs";import*as E from"graphql";import{resolve as d,extname as g}from"path";import{defaultConfig as s,loadOrGenerateConfig as O,DUMMY_ENDPOINT as w}from"./config.mjs";import*as S from"./deps.js";import{getRemoteSchema as _}from"./introspection.mjs";import{writeGenerate as x}from"./writeGenerate.mjs";const{buildClientSchema:R,buildSchema:N}=E;async function F({endpoint:i,destination:o,generateOptions:y,cli:b,headers:m,transformSchemaOptions:v}={}){o&&(s.destination=o);const{config:r,filepath:u}=await O({writeConfigFile:!0});if(i)s.introspection.endpoint=i;else if(j(d("./schema.gql")))i="./schema.gql",s.introspection.endpoint=i;else{const t=r.introspection&&r.introspection.endpoint;if(t&&t!==w)i=t;else throw console.error(`
Please modify "${u.endsWith("package.json")?"gqty":"config"}.introspection.endpoint" in: "${u}".`),Error("ERROR: No introspection endpoint specified in configuration file.")}o||(o=r.destination||s.destination),o=d(o);const h=Object.assign({},r,y);let c;if(s.introspection.endpoint=i,s.introspection.headers=m||{},i.startsWith("http://")||i.startsWith("https://"))c=await _(i,{headers:m});else{s.introspection.endpoint=w;const t=await S.fg(i);if(t.length){const a=[".graphql",".gql"],n=t.filter(e=>g(e)===".json"),l=t.filter(e=>a.includes(g(e)));if(t.length>n.length+l.length)throw Error("Received invalid files. Type generation can only use .gql, .graphql or .json files");if(n.length&&l.length)throw Error("Received mixed file inputs. Can not combine JSON and GQL files");if(n.length&&n.length>1)throw Error("Received multiple JSON introspection files, shoud only be one");const f=await Promise.all(t.map(e=>C.readFile(e,{encoding:"utf-8"})));if(g(t[0])===".json"){const e=JSON.parse(f[0]);let p;if(typeof e=="object"&&("data"in e&&e.data?p=e.data:"__schema"in e&&(p=e)),typeof p!="object")throw Error('Invalid JSON introspection result, expected "__schema" or "data.__schema" field.');c=R(p)}else c=N(f.join(`
`))}else throw Error(`File "${i}" doesn't exists. If you meant to inspect a GraphQL API, make sure to put http:// or https:// in front of it.`)}const q=await x(c,o,h,async t=>{var a,n;const l=(a=h.subscriptions)!=null?a:r.subscriptions,f=(n=h.react)!=null?n:r.react,e=`
If you meant to change this, please remove "${o}" and re-run code generation.`;l&&(t.includes("createSubscriptionsClient")||console.warn(`[Warning] You've changed the option "subscriptions" to 'true', which is different from your existing "${o}".`+e)),f&&(t.includes("createReactClient")||console.warn(`[Warning] You've changed the option "react" to 'true', which is different from your existing "${o}".`+e))},v);b&&console.log("Code generated successfully at "+q)}export{F as inspectWriteGenerate};