11import { createFromBuffer } from '@dprint/formatter'
22import { getPath } from '@dprint/typescript'
3+ import _ from 'json-bigint'
34import fs from 'node:fs/promises'
45import * as Path from 'node:path'
6+ import { errorFromMaybeError } from '../lib/prelude.js'
57import { generateCode , type Input as GenerateInput } from './code/code.js'
68
79export interface Input {
@@ -16,15 +18,21 @@ export const generateFiles = async (input: Input) => {
1618 const sourceDirPath = input . sourceDirPath ?? process . cwd ( )
1719 const schemaPath = input . schemaPath ?? Path . join ( sourceDirPath , `schema.graphql` )
1820 const schemaSource = await fs . readFile ( schemaPath , `utf8` )
19- const options = ( input . format ?? true )
20- ? {
21- formatter : createFromBuffer ( await fs . readFile ( getPath ( ) ) ) ,
22- }
23- : undefined
21+
22+ const customScalarCodecsPath = Path . relative ( input . outputDirPath , Path . join ( sourceDirPath , `customScalarCodecs.js` ) )
23+ // todo support other extensions: .tsx,.js,.mjs,.cjs
24+ const customScalarCodecsPathExists = await fileExists ( customScalarCodecsPath . replace ( `.js` , `.ts` ) )
25+ const formatter = ( input . format ?? true ) ? createFromBuffer ( await fs . readFile ( getPath ( ) ) ) : undefined
26+
27+ const options : GenerateInput [ 'options' ] = {
28+ formatter,
29+ customScalars : customScalarCodecsPathExists ,
30+ }
31+
2432 const code = generateCode ( {
2533 schemaSource,
2634 importPaths : {
27- customScalarCodecs : Path . relative ( input . outputDirPath , Path . join ( sourceDirPath , `customScalarCodecs.js` ) ) ,
35+ customScalarCodecs : customScalarCodecsPath ,
2836 } ,
2937 ...input . code ,
3038 options,
@@ -35,3 +43,14 @@ export const generateFiles = async (input: Input) => {
3543 await fs . writeFile ( `${ input . outputDirPath } /Scalar.ts` , code . scalars , { encoding : `utf8` } )
3644 await fs . writeFile ( `${ input . outputDirPath } /SchemaRuntime.ts` , code . schemaRuntime , { encoding : `utf8` } )
3745}
46+
47+ const fileExists = async ( path : string ) => {
48+ return Boolean (
49+ await fs . stat ( path ) . catch ( ( _ : unknown ) => {
50+ const error = errorFromMaybeError ( _ )
51+ return `code` in error && typeof error . code === `string` && error . code === `ENOENT`
52+ ? null
53+ : Promise . reject ( error )
54+ } ) ,
55+ )
56+ }
0 commit comments