Skip to content

Commit

Permalink
feat(ts-client): index sans dollar namespace (#767)
Browse files Browse the repository at this point in the history
  • Loading branch information
jasonkuhrt authored Apr 12, 2024
1 parent c77de38 commit fdca0a7
Show file tree
Hide file tree
Showing 11 changed files with 115 additions and 101 deletions.
4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@
},
"dependencies": {
"@dprint/formatter": "^0.2.1",
"@dprint/typescript": "^0.90.0",
"@dprint/typescript": "^0.90.1",
"@graphql-typed-document-node/core": "^3.2.0",
"@molt/command": "^0.9.0",
"dprint": "^0.45.1",
Expand Down Expand Up @@ -118,6 +118,6 @@
"type-fest": "^4.15.0",
"typescript": "^5.4.5",
"typescript-eslint": "^7.6.0",
"vitest": "^1.4.0"
"vitest": "^1.5.0"
}
}
68 changes: 34 additions & 34 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions src/ResultSet/ResultSet.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
/* eslint-disable @typescript-eslint/ban-types */

import { expectTypeOf, test } from 'vitest'
import type { $ } from '../../tests/ts/_/schema/generated/Index.js'
import type { Index } from '../../tests/ts/_/schema/generated/Index.js'
import type * as Schema from '../../tests/ts/_/schema/generated/SchemaBuildtime.js'
import type { SelectionSet } from '../SelectionSet/__.js'
import type { ResultSet } from './__.js'

type I = $.Index
type I = Index
type RS<$selectionSet extends SelectionSet.Query<I>> = ResultSet.Query<$selectionSet, I>

// dprint-ignore
Expand Down
4 changes: 2 additions & 2 deletions src/SelectionSet/SelectionSet.test-d.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { assertType, expectTypeOf, test } from 'vitest'
import type { $ } from '../../tests/ts/_/schema/generated/Index.js'
import type { Index } from '../../tests/ts/_/schema/generated/Index.js'
import type { SelectionSet } from './__.js'

type Q = SelectionSet.Query<$.Index>
type Q = SelectionSet.Query<Index>

test(`ParseAliasExpression`, () => {
expectTypeOf<SelectionSet.ParseAliasExpression<'a_as_b'>>().toEqualTypeOf<SelectionSet.Alias<'a', 'b'>>()
Expand Down
6 changes: 4 additions & 2 deletions src/SelectionSet/toGraphQLDocumentString.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
import { parse, print } from 'graphql'
import { describe, expect, test } from 'vitest'
import type { $ } from '../../tests/ts/_/schema/generated/Index.js'
import type { Index } from '../../tests/ts/_/schema/generated/Index.js'
import type { SelectionSet } from './__.js'
import { toGraphQLDocumentString } from './toGraphQLDocumentString.js'

type Q = SelectionSet.Query<$.Index>
// eslint-disable-next-line
// @ts-ignore
type Q = SelectionSet.Query<Index>
const s = (selectionSet: Q) => selectionSet
const prepareResult = (ss: Q) => {
const graphqlDocumentString = toGraphQLDocumentString(ss as any)
Expand Down
4 changes: 1 addition & 3 deletions src/SelectionSet/toGraphQLDocumentString.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,7 @@ type Args_ = string | boolean | null | number | Args

type Indicator = 0 | 1 | boolean

export type GraphQLDocumentObject = {
[k: string]: Indicator | SS
}
export type GraphQLDocumentObject = Record<string, Indicator | SS>

type SS = {
[k: string]: Indicator | SS
Expand Down
6 changes: 3 additions & 3 deletions src/client.test.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
/* eslint-disable */
import { beforeEach, describe, expect, test } from 'vitest'
import { setupMockServer } from '../tests/raw/__helpers.js'
import type { $ } from '../tests/ts/_/schema/generated/Index.js'
import type { Index } from '../tests/ts/_/schema/generated/Index.js'
import { $Index as schemaIndex } from '../tests/ts/_/schema/generated/SchemaRuntime.js'
import { create } from './client.js'

const ctx = setupMockServer()
const data = { fooBarUnion: { int: 1 } }

// @ts-ignore infinite depth
const client = () => create<$.Index>({ url: ctx.url, schemaIndex })
const client = () => create<Index>({ url: ctx.url, schemaIndex })

test.todo(`query`, async () => {
const mockRes = ctx.res({ body: { data } }).spec.body!
Expand Down Expand Up @@ -75,7 +75,7 @@ describe(`custom scalar`, () => {
ctx.res({ body: { data: {} } })
})
const clientExpected = (expectedDocument: (document: any) => void) => {
const client = create<$.Index>({
const client = create<Index>({
url: ctx.url,
schemaIndex,
hooks: {
Expand Down
4 changes: 4 additions & 0 deletions src/generator/code/code.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ export interface Input {
}
schemaSource: string
options?: {
/**
* Should custom scalars definitions be imported into the generated output?
*/
customScalars?: boolean
formatter?: Formatter
TSDoc?: {
noDocPolicy?: 'message' | 'ignore'
Expand Down
39 changes: 16 additions & 23 deletions src/generator/code/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,30 +7,23 @@ export const generateIndex = (config: Config) => {
let code = ``
code += `import type * as ${namespace} from './SchemaBuildtime.js'\n\n`
code += Code.export$(
Code.namespace(
`$`,
Code.group(
Code.export$(
Code.interface$(
`Index`,
Code.objectFrom({
Root: {
type: Code.objectFrom({
Query: hasQuery(config.typeMapByKind) ? `${namespace}.Root.Query` : null,
Mutation: hasMutation(config.typeMapByKind) ? `${namespace}.Root.Mutation` : null,
Subscription: hasSubscription(config.typeMapByKind) ? `${namespace}.Root.Subscription` : null,
}),
},
objects: Code.objectFromEntries(
config.typeMapByKind.GraphQLObjectType.map(_ => [_.name, `${namespace}.Object.${_.name}`]),
),
unions: Code.objectFromEntries(
config.typeMapByKind.GraphQLUnionType.map(_ => [_.name, `${namespace}.Union.${_.name}`]),
),
}),
),
Code.interface$(
`Index`,
Code.objectFrom({
Root: {
type: Code.objectFrom({
Query: hasQuery(config.typeMapByKind) ? `${namespace}.Root.Query` : null,
Mutation: hasMutation(config.typeMapByKind) ? `${namespace}.Root.Mutation` : null,
Subscription: hasSubscription(config.typeMapByKind) ? `${namespace}.Root.Subscription` : null,
}),
},
objects: Code.objectFromEntries(
config.typeMapByKind.GraphQLObjectType.map(_ => [_.name, `${namespace}.Object.${_.name}`]),
),
),
unions: Code.objectFromEntries(
config.typeMapByKind.GraphQLUnionType.map(_ => [_.name, `${namespace}.Union.${_.name}`]),
),
}),
),
)

Expand Down
31 changes: 25 additions & 6 deletions src/generator/files.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { createFromBuffer } from '@dprint/formatter'
import { getPath } from '@dprint/typescript'
import _ from 'json-bigint'
import fs from 'node:fs/promises'
import * as Path from 'node:path'
import { errorFromMaybeError } from '../lib/prelude.js'
import { generateCode, type Input as GenerateInput } from './code/code.js'

export interface Input {
Expand All @@ -16,15 +18,21 @@ export const generateFiles = async (input: Input) => {
const sourceDirPath = input.sourceDirPath ?? process.cwd()
const schemaPath = input.schemaPath ?? Path.join(sourceDirPath, `schema.graphql`)
const schemaSource = await fs.readFile(schemaPath, `utf8`)
const options = (input.format ?? true)
? {
formatter: createFromBuffer(await fs.readFile(getPath())),
}
: undefined

const customScalarCodecsPath = Path.relative(input.outputDirPath, Path.join(sourceDirPath, `customScalarCodecs.js`))
// todo support other extensions: .tsx,.js,.mjs,.cjs
const customScalarCodecsPathExists = await fileExists(customScalarCodecsPath.replace(`.js`, `.ts`))
const formatter = (input.format ?? true) ? createFromBuffer(await fs.readFile(getPath())) : undefined

const options: GenerateInput['options'] = {
formatter,
customScalars: customScalarCodecsPathExists,
}

const code = generateCode({
schemaSource,
importPaths: {
customScalarCodecs: Path.relative(input.outputDirPath, Path.join(sourceDirPath, `customScalarCodecs.js`)),
customScalarCodecs: customScalarCodecsPath,
},
...input.code,
options,
Expand All @@ -35,3 +43,14 @@ export const generateFiles = async (input: Input) => {
await fs.writeFile(`${input.outputDirPath}/Scalar.ts`, code.scalars, { encoding: `utf8` })
await fs.writeFile(`${input.outputDirPath}/SchemaRuntime.ts`, code.schemaRuntime, { encoding: `utf8` })
}

const fileExists = async (path: string) => {
return Boolean(
await fs.stat(path).catch((_: unknown) => {
const error = errorFromMaybeError(_)
return `code` in error && typeof error.code === `string` && error.code === `ENOENT`
? null
: Promise.reject(error)
}),
)
}
Loading

0 comments on commit fdca0a7

Please sign in to comment.