From 5977caf091e6ce3ed0264a7e8d1998d3a07fb4fb Mon Sep 17 00:00:00 2001 From: Tim Griesser Date: Sun, 6 Dec 2020 15:31:37 -0500 Subject: [PATCH 1/2] chore: Prettier on the codebase for JSDoc formatting --- .github/workflows/pr.yml | 6 +- .github/workflows/trunk.yml | 8 +- .../apollo-fullstack/src/fullstack-typegen.ts | 5 +- examples/apollo-fullstack/src/typeDefs.ts | 5 +- examples/githunt-api/src/githunt-typegen.ts | 5 +- examples/kitchen-sink/src/kitchen-sink.gen.ts | 25 +- examples/star-wars/src/data.ts | 29 +- examples/star-wars/src/schema.ts | 5 +- examples/star-wars/src/star-wars-typegen.ts | 11 +- examples/ts-ast-reader/src/schema.ts | 4 +- .../src/ts-ast-reader-typegen.ts | 5 +- package.json | 1 + src/builder.ts | 249 ++++++------------ src/definitions/args.ts | 17 +- src/definitions/definitionBlocks.ts | 25 +- src/definitions/enumType.ts | 28 +- src/definitions/extendInputType.ts | 4 +- src/definitions/inputObjectType.ts | 18 +- src/definitions/interfaceType.ts | 35 +-- src/definitions/list.ts | 4 +- src/definitions/nullable.ts | 4 +- src/definitions/scalarType.ts | 16 +- src/definitions/subscriptionField.ts | 4 +- src/definitions/unionType.ts | 25 +- src/definitions/wrapping.ts | 17 +- src/dynamicMethod.ts | 59 +---- src/dynamicProperty.ts | 15 +- src/extensions.ts | 25 +- src/plugin.ts | 149 ++++------- src/plugins/connectionPlugin.ts | 144 ++++------ src/plugins/declarativeWrappingPlugin.ts | 9 +- src/plugins/nullabilityGuardPlugin.ts | 13 +- src/sdlConverter.ts | 4 +- src/typeHelpersInternal.ts | 26 +- src/typegenAbstractTypes.ts | 44 ++-- src/typegenAutoConfig.ts | 76 +++--- src/typegenMetadata.ts | 18 +- src/typegenPrinter.ts | 4 +- src/typegenTypeHelpers.spec.types.ts | 4 +- src/typegenTypeHelpers.ts | 51 ++-- src/typegenUtils.ts | 4 +- src/utils.ts | 65 ++--- tests/__helpers/helpers.ts | 8 +- tests/__helpers/testApp.ts | 12 +- .../case.spec.ts | 4 +- .../isTypeOfsImplemented/case.spec.ts | 3 +- .../resolveTypeImplemented/case.spec.ts | 3 +- 47 files changed, 432 insertions(+), 863 deletions(-) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 18754161..16fbe657 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -11,7 +11,7 @@ jobs: with: node-version: 12.x - name: Install Dependencies - run: yarn --frozen-lockfile + run: yarn --frozen-lockfile && yarn format:ci - name: Install GraphQL@14.x run: yarn add graphql@^14.5.8 - name: Test @@ -29,7 +29,7 @@ jobs: with: node-version: ${{ matrix.node-version }} - name: Install Dependencies - run: yarn --frozen-lockfile + run: yarn --frozen-lockfile && yarn format:ci - name: Test run: yarn -s test:ci - name: Upload coverage to Codecov @@ -61,7 +61,7 @@ jobs: with: node-version: ${{ matrix.node-version }} - name: Install Dependencies - run: yarn --frozen-lockfile + run: yarn --frozen-lockfile && yarn format:ci - name: Link run: yarn link - name: Example Install diff --git a/.github/workflows/trunk.yml b/.github/workflows/trunk.yml index 7a0434e1..9c645783 100644 --- a/.github/workflows/trunk.yml +++ b/.github/workflows/trunk.yml @@ -13,7 +13,7 @@ jobs: with: node-version: 12.x - name: Install Dependencies - run: yarn --frozen-lockfile + run: yarn --frozen-lockfile && yarn format:ci - name: Install GraphQL@14.x run: yarn add graphql@^14.5.8 - name: Test @@ -31,7 +31,7 @@ jobs: with: node-version: ${{ matrix.node-version }} - name: Install Dependencies - run: yarn --frozen-lockfile + run: yarn --frozen-lockfile && yarn format:ci - name: Test run: yarn -s test:ci - name: Upload coverage to Codecov @@ -63,7 +63,7 @@ jobs: with: node-version: ${{ matrix.node-version }} - name: Install Dependencies - run: yarn --frozen-lockfile + run: yarn --frozen-lockfile && yarn format:ci - name: Link run: yarn link - name: Example Install @@ -82,7 +82,7 @@ jobs: fetch-depth: 0 - uses: actions/setup-node@v1 - name: Install Dependencies - run: yarn --frozen-lockfile + run: yarn --frozen-lockfile && yarn format:ci - name: Release Canary env: NPM_TOKEN: ${{secrets.NPM_TOKEN}} diff --git a/examples/apollo-fullstack/src/fullstack-typegen.ts b/examples/apollo-fullstack/src/fullstack-typegen.ts index e2639475..01368302 100644 --- a/examples/apollo-fullstack/src/fullstack-typegen.ts +++ b/examples/apollo-fullstack/src/fullstack-typegen.ts @@ -1,7 +1,4 @@ -/** - * This file was generated by Nexus Schema - * Do not make changes to this file directly - */ +/** This file was generated by Nexus Schema Do not make changes to this file directly */ import * as t from './typeDefs' diff --git a/examples/apollo-fullstack/src/typeDefs.ts b/examples/apollo-fullstack/src/typeDefs.ts index b3fb1b24..3af64a7e 100644 --- a/examples/apollo-fullstack/src/typeDefs.ts +++ b/examples/apollo-fullstack/src/typeDefs.ts @@ -45,9 +45,8 @@ export interface LaunchApi extends RESTDataSource { export interface UserApi extends DataSource { /** - * User can be called with an argument that includes email, but it doesn't - * have to be. If the user is already on the context, it will use that user - * instead + * User can be called with an argument that includes email, but it doesn't have to be. If the user is + * already on the context, it will use that user instead */ findOrCreateUser(obj?: { email?: string | null }): Promise bookTrips(obj: { launchIds: string[] }): Promise diff --git a/examples/githunt-api/src/githunt-typegen.ts b/examples/githunt-api/src/githunt-typegen.ts index f1af2162..ee6840d5 100644 --- a/examples/githunt-api/src/githunt-typegen.ts +++ b/examples/githunt-api/src/githunt-typegen.ts @@ -1,7 +1,4 @@ -/** - * This file was generated by Nexus Schema - * Do not make changes to this file directly - */ +/** This file was generated by Nexus Schema Do not make changes to this file directly */ declare global { interface NexusGen extends NexusGenTypes {} diff --git a/examples/kitchen-sink/src/kitchen-sink.gen.ts b/examples/kitchen-sink/src/kitchen-sink.gen.ts index 2c8ba521..4d77b6da 100644 --- a/examples/kitchen-sink/src/kitchen-sink.gen.ts +++ b/examples/kitchen-sink/src/kitchen-sink.gen.ts @@ -1,7 +1,4 @@ -/** - * This file was generated by Nexus Schema - * Do not make changes to this file directly - */ +/** This file was generated by Nexus Schema Do not make changes to this file directly */ import { UnusedInterfaceTypeDef } from './kitchen-sink-definitions' import { core, connectionPluginCore } from '@nexus/schema' @@ -557,24 +554,20 @@ declare global { } interface NexusGenPluginFieldConfig { /** - * The complexity for an individual field. Return a number - * or a function that returns a number to specify the - * complexity for this field. + * The complexity for an individual field. Return a number or a function that returns a number to specify + * the complexity for this field. */ complexity?: QueryComplexity /** - * Authorization for an individual field. Returning "true" - * or "Promise" means the field can be accessed. - * Returning "false" or "Promise" will respond - * with a "Not Authorized" error for the field. - * Returning or throwing an error will also prevent the - * resolver from executing. + * Authorization for an individual field. Returning "true" or "Promise" means the field can be + * accessed. Returning "false" or "Promise" will respond with a "Not Authorized" error for the + * field. Returning or throwing an error will also prevent the resolver from executing. */ authorize?: FieldAuthorizeResolver /** - * The nullability guard can be helpful, but is also a potentially expensive operation for lists. - * We need to iterate the entire list to check for null items to guard against. Set this to true - * to skip the null guard on a specific field if you know there's no potential for unsafe types. + * The nullability guard can be helpful, but is also a potentially expensive operation for lists. We need + * to iterate the entire list to check for null items to guard against. Set this to true to skip the null + * guard on a specific field if you know there's no potential for unsafe types. */ skipNullGuard?: boolean } diff --git a/examples/star-wars/src/data.ts b/examples/star-wars/src/data.ts index 1c1ba7f1..2e35e77e 100644 --- a/examples/star-wars/src/data.ts +++ b/examples/star-wars/src/data.ts @@ -5,16 +5,15 @@ import { Character, Human, Droid } from './types/backingTypes' * * Copyright (c) 2015-present, Facebook, Inc. * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. + * This source code is licensed under the MIT license found in the LICENSE file in the root directory of this + * source tree. */ /** * This defines a basic set of data for our Star Wars Schema. * - * This data is hard coded for the sake of the demo, but you could imagine - * fetching this data from a backend service rather than from hardcoded - * JSON objects in a more complex demo. + * This data is hard coded for the sake of the demo, but you could imagine fetching this data from a backend + * service rather than from hardcoded JSON objects in a more complex demo. */ const luke = { @@ -91,25 +90,19 @@ const droidData = { '2001': artoo, } as { [key in string]: Droid } -/** - * Helper function to get a character by ID. - */ +/** Helper function to get a character by ID. */ function getCharacter(id: string) { // Returning a promise just to illustrate GraphQL.js's support. return Promise.resolve(humanData[id] || droidData[id]) } -/** - * Allows us to query for a character's friends. - */ +/** Allows us to query for a character's friends. */ export function getFriends(character: Character) { // Notice that GraphQL accepts Arrays of Promises. return character.friends.map((id) => getCharacter(id)) } -/** - * Allows us to fetch the undisputed hero of the Star Wars trilogy, R2-D2. - */ +/** Allows us to fetch the undisputed hero of the Star Wars trilogy, R2-D2. */ export function getHero(episode?: number | null): Character { if (episode === 5) { // Luke is the hero of Episode V. @@ -121,18 +114,14 @@ export function getHero(episode?: number | null): Character { export const allHumans = Object.keys(humanData).map((key) => humanData[key]) -/** - * Allows us to query for the human with the given id. - */ +/** Allows us to query for the human with the given id. */ export function getHuman(id: string): Human { return humanData[id] } export const allDroids = Object.keys(droidData).map((key) => droidData[key]) -/** - * Allows us to query for the droid with the given id. - */ +/** Allows us to query for the droid with the given id. */ export function getDroid(id: string): Droid { return droidData[id] } diff --git a/examples/star-wars/src/schema.ts b/examples/star-wars/src/schema.ts index 542d93be..8b439eef 100644 --- a/examples/star-wars/src/schema.ts +++ b/examples/star-wars/src/schema.ts @@ -2,10 +2,7 @@ import { makeSchema, nullabilityGuardPlugin } from '@nexus/schema' import * as path from 'path' import * as allTypes from './graphql' -/** - * Finally, we construct our schema (whose starting query type is the query - * type we defined above) and export it. - */ +/** Finally, we construct our schema (whose starting query type is the query type we defined above) and export it. */ export const schema = makeSchema({ types: allTypes, outputs: { diff --git a/examples/star-wars/src/star-wars-typegen.ts b/examples/star-wars/src/star-wars-typegen.ts index ca3654c2..d16318c3 100644 --- a/examples/star-wars/src/star-wars-typegen.ts +++ b/examples/star-wars/src/star-wars-typegen.ts @@ -1,7 +1,4 @@ -/** - * This file was generated by Nexus Schema - * Do not make changes to this file directly - */ +/** This file was generated by Nexus Schema Do not make changes to this file directly */ import * as swapi from './types/backingTypes' @@ -206,9 +203,9 @@ declare global { interface NexusGenPluginTypeConfig {} interface NexusGenPluginFieldConfig { /** - * The nullability guard can be helpful, but is also a potentially expensive operation for lists. - * We need to iterate the entire list to check for null items to guard against. Set this to true - * to skip the null guard on a specific field if you know there's no potential for unsafe types. + * The nullability guard can be helpful, but is also a potentially expensive operation for lists. We need + * to iterate the entire list to check for null items to guard against. Set this to true to skip the null + * guard on a specific field if you know there's no potential for unsafe types. */ skipNullGuard?: boolean } diff --git a/examples/ts-ast-reader/src/schema.ts b/examples/ts-ast-reader/src/schema.ts index 8104c50d..71e9d8d9 100644 --- a/examples/ts-ast-reader/src/schema.ts +++ b/examples/ts-ast-reader/src/schema.ts @@ -41,8 +41,8 @@ export const schema = makeSchema({ }) /** - * When the type is a "Node", we want to first look for types with - * the name `Node`, e.g. TypeReferenceNode vs TypeReference + * When the type is a "Node", we want to first look for types with the name `Node`, e.g. TypeReferenceNode vs + * TypeReference */ function tsTypeMatch(type: GraphQLNamedType, defaultMatch: RegExp) { if (isNodeType(type)) { diff --git a/examples/ts-ast-reader/src/ts-ast-reader-typegen.ts b/examples/ts-ast-reader/src/ts-ast-reader-typegen.ts index fc0e3869..b2a38264 100644 --- a/examples/ts-ast-reader/src/ts-ast-reader-typegen.ts +++ b/examples/ts-ast-reader/src/ts-ast-reader-typegen.ts @@ -1,7 +1,4 @@ -/** - * This file was generated by Nexus Schema - * Do not make changes to this file directly - */ +/** This file was generated by Nexus Schema Do not make changes to this file directly */ import * as t from './types/index' import ts from 'typescript' diff --git a/package.json b/package.json index 1e1edf0d..36fdba56 100644 --- a/package.json +++ b/package.json @@ -38,6 +38,7 @@ "dev:test": "jest --watch", "examples": "yarn link-examples && yarn gulp run-examples", "format": "prettier --write 'src/**/*.ts' 'tests/**/*.ts' 'examples/*/src/**.ts'", + "format:ci": "prettier --check 'src/**/*.ts' 'tests/**/*.ts' 'examples/*/src/**.ts'", "link-examples": "yarn && yarn gulp link-examples", "lint": "tslint -p tsconfig.json", "prepublish": "yarn clean && yarn build", diff --git a/src/builder.ts b/src/builder.ts index 07258a66..9ec02ac0 100644 --- a/src/builder.ts +++ b/src/builder.ts @@ -170,99 +170,74 @@ type PossibleInputType = string | AllNexusNamedInputTypeDefs | GraphQLType export interface BuilderConfigInput { /** - * Generated artifact settings. Set to false to disable all. - * Set to true to enable all and use default paths. Leave - * undefined for default behaviour of each artifact. + * Generated artifact settings. Set to false to disable all. Set to true to enable all and use default + * paths. Leave undefined for default behaviour of each artifact. */ outputs?: | boolean | { /** - * TypeScript declaration file generation settings. This file - * contains types reflected off your source code. It is how - * Nexus imbues dynamic code with static guarantees. + * TypeScript declaration file generation settings. This file contains types reflected off your source + * code. It is how Nexus imbues dynamic code with static guarantees. * - * Defaults to being enabled when `process.env.NODE_ENV !== "production"`. - * Set to true to enable and emit into default path (see below). - * Set to false to disable. Set to a string to specify absolute path. + * Defaults to being enabled when `process.env.NODE_ENV !== "production"`. Set to true to enable and + * emit into default path (see below). Set to false to disable. Set to a string to specify absolute path. * - * The default path is node_modules/@types/nexus-typegen/index.d.ts. - * This is chosen because TypeScript will pick it up without - * any configuration needed by you. For more details about the @types - * system refer to https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types + * The default path is node_modules/@types/nexus-typegen/index.d.ts. This is chosen because TypeScript + * will pick it up without any configuration needed by you. For more details about the @types system + * refer to https://www.typescriptlang.org/docs/handbook/tsconfig-json.html#types-typeroots-and-types */ typegen?: boolean | string /** * GraphQL SDL file generation toggle and location. * - * Set to a string to enable and output to an absolute path. - * Set to true to enable at default path (schema.graphql in the current working directory) - * Set to false to disable + * Set to a string to enable and output to an absolute path. Set to true to enable at default path + * (schema.graphql in the current working directory) Set to false to disable * * Defaults to true in development and false otherwise. * - * @remarks - * - * This file is not necessary but - * may be nice for teams wishing to review SDL in pull-requests or - * just generally transitioning from a schema-first workflow. - * + * This file is not necessary but may be nice for teams wishing to review SDL in pull-requests or just + * generally transitioning from a schema-first workflow. */ schema?: boolean | string } /** - * Whether the schema & types are generated when the server - * starts. Default is !process.env.NODE_ENV || process.env.NODE_ENV === "development" + * Whether the schema & types are generated when the server starts. Default is !process.env.NODE_ENV || + * process.env.NODE_ENV === "development" */ shouldGenerateArtifacts?: boolean /** - * Automatically configure type resolution for the TypeScript - * representations of the associated types. + * Automatically configure type resolution for the TypeScript representations of the associated types. * * Alias for typegenConfig: typegenAutoConfig(options) */ typegenAutoConfig?: TypegenAutoConfigOptions - /** - * A configuration function for advanced cases where - * more control over the `TypegenInfo` is needed. - */ + /** A configuration function for advanced cases where more control over the `TypegenInfo` is needed. */ typegenConfig?: (schema: GraphQLSchema, outputPath: string) => TypegenInfo | PromiseLike /** - * Adjust the Prettier options used while running prettier over - * the generated output. - * - * Can be an absolute path to a Prettier config file like - * .prettierrc or package.json with "prettier" field, or an object - * of Prettier options. + * Adjust the Prettier options used while running prettier over the generated output. * - * If provided, you must have prettier available as an importable dep - * in your project. + * Can be an absolute path to a Prettier config file like .prettierrc or package.json with "prettier" field, + * or an object of Prettier options. * + * If provided, you must have prettier available as an importable dep in your project. */ prettierConfig?: string | object /** - * Manually apply a formatter to the generated content before saving, - * see the `prettierConfig` option if you want to use Prettier. + * Manually apply a formatter to the generated content before saving, see the `prettierConfig` option if you + * want to use Prettier. */ formatTypegen?: TypegenFormatFn /** - * Configures the default "nonNullDefaults" for the entire schema the type. - * Read more about how nexus handles nullability + * Configures the default "nonNullDefaults" for the entire schema the type. Read more about how nexus + * handles nullability */ nonNullDefaults?: NonNullConfig - /** - * List of plugins to apply to Nexus, with before/after hooks - * executed first to last: before -> resolve -> after - */ + /** List of plugins to apply to Nexus, with before/after hooks executed first to last: before -> resolve -> after */ plugins?: NexusPlugin[] - /** - * Provide if you wish to customize the behavior of the schema printing. - * Otherwise, uses `printSchema` from graphql-js - */ + /** Provide if you wish to customize the behavior of the schema printing. Otherwise, uses `printSchema` from graphql-js */ customPrintSchemaFn?: typeof printSchema - /** - * Customize and toggle on or off various features of Nexus. - */ + /** Customize and toggle on or off various features of Nexus. */ features?: NexusFeaturesInput } @@ -274,52 +249,35 @@ export interface BuilderConfig extends Omit]?: string } - /** - * The string type of the context for the resolvers - */ + /** The string type of the context for the resolvers */ contextType?: string - /** - * Info about where to import the context from - */ + /** Info about where to import the context from */ contextTypeImport?: TypingImport /** - * The path to the @nexus/schema package. - * - * @default '@nexus/schema' + * The path to the @nexus/schema package for typegen. * - * @remarks - * - * This setting is particularly useful when @nexus/schema is being wrapped by - * another library/framework such that @nexus/schema is not expected to be a - * direct dependency at the application level. + * This setting is only necessary when @nexus/schema is being wrapped by another library/framework such that + * `@nexus/schema` is not expected to be a direct dependency at the application level. */ nexusSchemaImportId?: string } @@ -358,37 +316,28 @@ export type PluginBuilderLens = { } /** - * Builds all of the types, properly accounts for any using "mix". - * Since the enum types are resolved synchronously, these need to guard for - * circular references at this step, while fields will guard for it during lazy evaluation. + * Builds all of the types, properly accounts for any using "mix". Since the enum types are resolved + * synchronously, these need to guard for circular references at this step, while fields will guard for it + * during lazy evaluation. */ export class SchemaBuilder { - /** - * Used to check for circular references. - */ + /** Used to check for circular references. */ protected buildingTypes = new Set() - /** - * The "final type" map contains all types as they are built. - */ + /** The "final type" map contains all types as they are built. */ protected finalTypeMap: Record = {} /** - * The "defined type" map keeps track of all of the types that were - * defined directly as `GraphQL*Type` objects, so we don't accidentally - * overwrite any. + * The "defined type" map keeps track of all of the types that were defined directly as `GraphQL*Type` + * objects, so we don't accidentally overwrite any. */ protected definedTypeMap: Record = {} /** - * The "pending type" map keeps track of all types that were defined w/ - * GraphQL Nexus and haven't been processed into concrete types yet. + * The "pending type" map keeps track of all types that were defined w/ GraphQL Nexus and haven't been + * processed into concrete types yet. */ protected pendingTypeMap: Record = {} - /** - * All "extensions" to types (adding fields on types from many locations) - */ + /** All "extensions" to types (adding fields on types from many locations) */ protected typeExtendMap: Record[] | null> = {} - /** - * All "extensions" to input types (adding fields on types from many locations) - */ + /** All "extensions" to input types (adding fields on types from many locations) */ protected inputTypeExtendMap: Record[] | null> = {} protected dynamicInputFields: DynamicInputFields = {} @@ -396,80 +345,49 @@ export class SchemaBuilder { protected dynamicOutputProperties: DynamicOutputProperties = {} protected plugins: NexusPlugin[] = [] - /** - * All types that need to be traversed for children types - */ + /** All types that need to be traversed for children types */ protected typesToWalk: TypeToWalk[] = [] - /** - * Root type mapping information annotated on the type definitions - */ + /** Root type mapping information annotated on the type definitions */ protected rootTypings: RootTypings = {} - /** - * Array of missing types - */ + /** Array of missing types */ protected missingTypes: Record = {} - /** - * Methods we are able to access to read/modify builder state from plugins - */ + /** Methods we are able to access to read/modify builder state from plugins */ protected builderLens: PluginBuilderLens - /** - * Created just before types are walked, this keeps track of all of the resolvers - */ + /** Created just before types are walked, this keeps track of all of the resolvers */ protected onMissingTypeFns: Exclude[] = [] - /** - * Executed just before types are walked - */ + /** Executed just before types are walked */ protected onBeforeBuildFns: Exclude[] = [] - /** - * Executed as the field resolvers are included on the field - */ + /** Executed as the field resolvers are included on the field */ protected onCreateResolverFns: Exclude[] = [] - /** - * Executed as the field "subscribe" fields are included on the schema - */ + /** Executed as the field "subscribe" fields are included on the schema */ protected onCreateSubscribeFns: Exclude[] = [] - /** - * Executed after the schema is constructed, for any final verification - */ + /** Executed after the schema is constructed, for any final verification */ protected onAfterBuildFns: Exclude[] = [] - /** - * Executed after the object is defined, allowing us to add additional fields to the object - */ + /** Executed after the object is defined, allowing us to add additional fields to the object */ protected onObjectDefinitionFns: Exclude[] = [] - /** - * Executed after the object is defined, allowing us to add additional fields to the object - */ + /** Executed after the object is defined, allowing us to add additional fields to the object */ protected onInputObjectDefinitionFns: Exclude[] = [] - /** - * Called immediately after the field is defined, allows for using metadata to define the shape of the field. - */ + /** Called immediately after the field is defined, allows for using metadata to define the shape of the field. */ protected onAddArgFns: Exclude[] = [] - /** - * Called immediately after the field is defined, allows for using metadata to define the shape of the field. - */ + /** Called immediately after the field is defined, allows for using metadata to define the shape of the field. */ protected onAddOutputFieldFns: Exclude[] = [] - /** - * Called immediately after the field is defined, allows for using metadata to define the shape of the field. - */ + /** Called immediately after the field is defined, allows for using metadata to define the shape of the field. */ protected onAddInputFieldFns: Exclude[] = [] - /** - * The `schemaExtension` is created just after the types are walked, - * but before the fields are materialized. - */ + /** The `schemaExtension` is created just after the types are walked, but before the fields are materialized. */ protected _schemaExtension?: NexusSchemaExtension protected config: BuilderConfig @@ -484,9 +402,7 @@ export class SchemaBuilder { constructor(config: BuilderConfigInput) { this.config = setConfigDefaults(config) - /** - * This array of plugin is used to keep retro-compatibility w/ older versions of nexus - */ + /** This array of plugin is used to keep retro-compatibility w/ older versions of nexus */ this.plugins = this.config.plugins.length > 0 ? this.config.plugins : [fieldAuthorizePlugin()] // TODO(tim): In 1.0 change to declarativeWrappingPlugin({ disable: true }) @@ -523,11 +439,9 @@ export class SchemaBuilder { } /** - * Add type takes a Nexus type, or a GraphQL type and pulls - * it into an internal "type registry". It also does an initial pass - * on any types that are referenced on the "types" field and pulls - * those in too, so you can define types anonymously, without - * exporting them. + * Add type takes a Nexus type, or a GraphQL type and pulls it into an internal "type registry". It also + * does an initial pass on any types that are referenced on the "types" field and pulls those in too, so + * you can define types anonymously, without exporting them. */ addType = (typeDef: NexusAcceptedTypeDef) => { if (isNexusDynamicInputMethod(typeDef)) { @@ -1700,10 +1614,7 @@ export interface BuildTypes onAfterBuildFns: SchemaBuilder['onAfterBuildFns'] } -/** - * Builds the schema, we may return more than just the schema - * from this one day. - */ +/** Builds the schema, we may return more than just the schema from this one day. */ export function makeSchemaInternal(config: SchemaConfig) { const builder = new SchemaBuilder(config) builder.addTypes(config.types) @@ -1797,11 +1708,10 @@ export function setConfigDefaults(config: BuilderConfigInput): BuilderConfig { } /** - * Defines the GraphQL schema, by combining the GraphQL types defined - * by the GraphQL Nexus layer or any manually defined GraphQLType objects. + * Defines the GraphQL schema, by combining the GraphQL types defined by the GraphQL Nexus layer or any + * manually defined GraphQLType objects. * - * Requires at least one type be named "Query", which will be used as the - * root query type. + * Requires at least one type be named "Query", which will be used as the root query type. */ export function makeSchema(config: SchemaConfig): NexusGraphQLSchema { const { schema, missingTypes, finalConfig } = makeSchemaInternal(config) @@ -1835,10 +1745,7 @@ export function makeSchema(config: SchemaConfig): NexusGraphQLSchema { return schema } -/** - * Like makeSchema except that typegen is always run - * and waited upon. - */ +/** Like makeSchema except that typegen is always run and waited upon. */ export async function generateSchema(config: SchemaConfig): Promise { const { schema, missingTypes, finalConfig } = makeSchemaInternal(config) const typegenConfig = resolveTypegenConfig(finalConfig) @@ -1849,8 +1756,8 @@ export async function generateSchema(config: SchemaConfig): Promise export type CommonArgConfig = { - /** - * The description to annotate the GraphQL SDL - */ + /** The description to annotate the GraphQL SDL */ description?: string | null } & NexusGenPluginArgConfig export interface ScalarArgConfig extends CommonArgConfig { - /** - * Configure the default for the object - */ + /** Configure the default for the object */ default?: T } export type NexusArgConfigType = T | AllNexusInputTypeDefs export interface NexusAsArgConfig extends CommonArgConfig { - /** - * Configure the default for the object - */ + /** Configure the default for the object */ default?: GetGen2<'allTypes', T> // TODO: Make this type-safe somehow } export interface NexusArgConfig extends NexusAsArgConfig { - /** - * The type of the argument, either the string name of the type, - * or the concrete Nexus type definition - */ + /** The type of the argument, either the string name of the type, or the concrete Nexus type definition */ type: NexusArgConfigType } diff --git a/src/definitions/definitionBlocks.ts b/src/definitions/definitionBlocks.ts index d7390321..53014e7a 100644 --- a/src/definitions/definitionBlocks.ts +++ b/src/definitions/definitionBlocks.ts @@ -6,28 +6,22 @@ import { BaseScalars } from './_types' import { messages } from '../messages' export interface CommonFieldConfig { - /** - * The description to annotate the GraphQL SDL - */ + /** The description to annotate the GraphQL SDL */ description?: string | null /** - * Info about a field deprecation. Formatted as a string and provided with the - * deprecated directive on field/enum types and as a comment on input fields. + * Info about a field deprecation. Formatted as a string and provided with the deprecated directive on + * field/enum types and as a comment on input fields. */ deprecation?: string // | DeprecationInfo; } export type CommonOutputFieldConfig = CommonFieldConfig & { - /** - * Arguments for the field - */ + /** Arguments for the field */ args?: ArgsRecord } & NexusGenPluginFieldConfig export type CommonInputFieldConfig = CommonFieldConfig & { - /** - * The default value for the field, if any - */ + /** The default value for the field, if any */ default?: GetGen3<'inputTypes', TypeName, FieldName> } & NexusGenPluginFieldConfig @@ -42,9 +36,7 @@ export interface ScalarInputFieldConfig extends CommonInputFieldConfig extends CommonOutputFieldConfig { - /** - * Resolve method for the field - */ + /** Resolve method for the field */ resolve?: FieldResolver } @@ -107,10 +99,7 @@ export interface OutputDefinitionBlock NexusGenCustomOutputProperties {} -/** - * The output definition block is passed to the "definition" - * function property of the "objectType" / "interfaceType" - */ +/** The output definition block is passed to the "definition" function property of the "objectType" / "interfaceType" */ export class OutputDefinitionBlock { readonly typeName: string constructor(protected typeBuilder: OutputDefinitionBuilder, protected wrapping?: NexusWrapKind[]) { diff --git a/src/definitions/enumType.ts b/src/definitions/enumType.ts index c72b6dbf..cbc5b5e4 100644 --- a/src/definitions/enumType.ts +++ b/src/definitions/enumType.ts @@ -6,38 +6,26 @@ type TypeScriptEnumLike = { } export interface EnumMemberInfo { - /** - * The external "value" of the enum as displayed in the SDL - */ + /** The external "value" of the enum as displayed in the SDL */ name: string - /** - * The internal representation of the enum - */ + /** The internal representation of the enum */ value?: string | number | object | boolean - /** - * The description to annotate the GraphQL SDL - */ + /** The description to annotate the GraphQL SDL */ description?: string | null /** - * Info about a field deprecation. Formatted as a string and provided with the - * deprecated directive on field/enum types and as a comment on input fields. + * Info about a field deprecation. Formatted as a string and provided with the deprecated directive on + * field/enum types and as a comment on input fields. */ deprecation?: string // | DeprecationInfo; } export interface EnumTypeConfig { name: TypeName - /** - * The description to annotate the GraphQL SDL - */ + /** The description to annotate the GraphQL SDL */ description?: string | null - /** - * Root type information for this type - */ + /** Root type information for this type */ rootTyping?: RootTypingDef - /** - * All members of the enum, either as an array of strings/definition objects, as an object, or as a TypeScript enum - */ + /** All members of the enum, either as an array of strings/definition objects, as an object, or as a TypeScript enum */ members: | Array | Record diff --git a/src/definitions/extendInputType.ts b/src/definitions/extendInputType.ts index fb35ac87..4c9db29b 100644 --- a/src/definitions/extendInputType.ts +++ b/src/definitions/extendInputType.ts @@ -20,8 +20,8 @@ export class NexusExtendInputTypeDef { withNexusSymbol(NexusExtendInputTypeDef, NexusTypes.ExtendInputObject) /** - * Adds new fields to an existing inputObjectType in the schema. Useful when - * splitting your schema across several domains. + * Adds new fields to an existing inputObjectType in the schema. Useful when splitting your schema across + * several domains. * * @see https://nexusjs.org/docs/api/extend-type */ diff --git a/src/definitions/inputObjectType.ts b/src/definitions/inputObjectType.ts index a2520906..bcf9046c 100644 --- a/src/definitions/inputObjectType.ts +++ b/src/definitions/inputObjectType.ts @@ -4,23 +4,15 @@ import { InputDefinitionBlock } from './definitionBlocks' import { NexusTypes, NonNullConfig, withNexusSymbol } from './_types' export interface NexusInputObjectTypeConfig { - /** - * Name of the input object type - */ + /** Name of the input object type */ name: TypeName - /** - * Definition block for the input type - */ + /** Definition block for the input type */ definition(t: InputDefinitionBlock): void - /** - * The description to annotate the GraphQL SDL - */ + /** The description to annotate the GraphQL SDL */ description?: string | null /** - * Configures the nullability for the type, check the - * documentation's "Getting Started" section to learn - * more about GraphQL Nexus's assumptions and configuration - * on nullability. + * Configures the nullability for the type, check the documentation's "Getting Started" section to learn + * more about GraphQL Nexus's assumptions and configuration on nullability. */ nonNullDefaults?: NonNullConfig } diff --git a/src/definitions/interfaceType.ts b/src/definitions/interfaceType.ts index c256438a..d89dbfd3 100644 --- a/src/definitions/interfaceType.ts +++ b/src/definitions/interfaceType.ts @@ -15,17 +15,11 @@ export type Implemented = GetGen<'interfaceNames'> | NexusInterfaceTypeDef export interface FieldModification { type?: ModificationType - /** - * The description to annotate the GraphQL SDL - */ + /** The description to annotate the GraphQL SDL */ description?: string | null - /** - * The resolve method we should be resolving the field with - */ + /** The resolve method we should be resolving the field with */ resolve?: FieldResolver - /** - * You are allowed to add non-required args when modifying a field - */ + /** You are allowed to add non-required args when modifying a field */ args?: ArgsRecord } @@ -46,19 +40,13 @@ export type NexusInterfaceTypeConfig = { definition(t: InterfaceDefinitionBlock): void /** - * Configures the nullability for the type, check the - * documentation's "Getting Started" section to learn - * more about GraphQL Nexus's assumptions and configuration - * on nullability. + * Configures the nullability for the type, check the documentation's "Getting Started" section to learn + * more about GraphQL Nexus's assumptions and configuration on nullability. */ nonNullDefaults?: NonNullConfig - /** - * The description to annotate the GraphQL SDL - */ + /** The description to annotate the GraphQL SDL */ description?: string | null - /** - * Root type information for this type - */ + /** Root type information for this type */ rootTyping?: RootTypingDef } & AbstractTypes.MaybeTypeDefConfigFieldResolveType @@ -73,15 +61,11 @@ export class InterfaceDefinitionBlock extends OutputDef constructor(protected typeBuilder: InterfaceDefinitionBuilder) { super(typeBuilder) } - /** - * @param interfaceName - */ + /** @param interfaceName */ implements(...interfaceName: Array) { this.typeBuilder.addInterfaces(interfaceName) } - /** - * Modifies a field added via an interface - */ + /** Modifies a field added via an interface */ modify, string>>( field: FieldName, modifications: FieldModification @@ -109,6 +93,7 @@ withNexusSymbol(NexusInterfaceTypeDef, NexusTypes.Interface) /** * Defines a GraphQLInterfaceType + * * @param config */ export function interfaceType(config: NexusInterfaceTypeConfig) { diff --git a/src/definitions/list.ts b/src/definitions/list.ts index b3843140..c9ab2756 100644 --- a/src/definitions/list.ts +++ b/src/definitions/list.ts @@ -1,9 +1,7 @@ import { isType } from 'graphql' import { AllNamedTypeDefs, isNexusStruct, NexusListableTypes } from './wrapping' import { NexusTypes, withNexusSymbol } from './_types' -/** - * list() - */ +/** List() */ export type NexusListDefConfig = { type: TypeName } diff --git a/src/definitions/nullable.ts b/src/definitions/nullable.ts index 6eb62056..3bef1529 100644 --- a/src/definitions/nullable.ts +++ b/src/definitions/nullable.ts @@ -16,9 +16,7 @@ export class NexusNullDef { withNexusSymbol(NexusNullDef, NexusTypes.Null) -/** - * null() - */ +/** Null() */ export function nullable(type: TypeName) { if (isNexusNonNullTypeDef(type)) { return new NexusNullDef(type.ofNexusType) diff --git a/src/definitions/scalarType.ts b/src/definitions/scalarType.ts index 190e8922..68078e9c 100644 --- a/src/definitions/scalarType.ts +++ b/src/definitions/scalarType.ts @@ -9,24 +9,16 @@ export interface ScalarBase > {} export interface ScalarConfig { - /** - * Any deprecation info for this scalar type - */ + /** Any deprecation info for this scalar type */ deprecation?: string // | DeprecationInfo; - /** - * Adds this type as a method on the Object/Interface definition blocks - */ + /** Adds this type as a method on the Object/Interface definition blocks */ asNexusMethod?: string - /** - * Root type information for this type - */ + /** Root type information for this type */ rootTyping?: RootTypingDef } export interface NexusScalarTypeConfig extends ScalarBase, ScalarConfig { - /** - * The name of the scalar type - */ + /** The name of the scalar type */ name: T } diff --git a/src/definitions/subscriptionField.ts b/src/definitions/subscriptionField.ts index 0d30bc72..26100df5 100644 --- a/src/definitions/subscriptionField.ts +++ b/src/definitions/subscriptionField.ts @@ -14,9 +14,7 @@ export function subscriptionField( config: SubscriptionFieldConfig ): NexusExtendTypeDef<'Subscription'> -/** - * Add one field to the Subscription type - */ +/** Add one field to the Subscription type */ export function subscriptionField(...args: any[]) { return extendType({ type: 'Subscription', diff --git a/src/definitions/unionType.ts b/src/definitions/unionType.ts index 632dcfcb..3f708dcf 100644 --- a/src/definitions/unionType.ts +++ b/src/definitions/unionType.ts @@ -16,8 +16,8 @@ export type UnionMembers = Array | NexusObjectTypeDef export class UnionDefinitionBlock { constructor(protected typeBuilder: UnionDefinitionBuilder) {} /** - * All ObjectType names that should be part of the union, either - * as string names or as references to the `objectType()` return value + * All ObjectType names that should be part of the union, either as string names or as references to the + * `objectType()` return value */ members(...unionMembers: UnionMembers) { this.typeBuilder.addUnionMembers(unionMembers) @@ -31,26 +31,18 @@ export class UnionDefinitionBlock { } export type NexusUnionTypeConfig = { - /** - * The name of the union type - */ + /** The name of the union type */ name: TypeName - /** - * Builds the definition for the union - */ + /** Builds the definition for the union */ definition(t: UnionDefinitionBlock): void - /** - * The description to annotate the GraphQL SDL - */ + /** The description to annotate the GraphQL SDL */ description?: string | null /** - * Info about a field deprecation. Formatted as a string and provided with the - * deprecated directive on field/enum types and as a comment on input fields. + * Info about a field deprecation. Formatted as a string and provided with the deprecated directive on + * field/enum types and as a comment on input fields. */ deprecation?: string // | DeprecationInfo; - /** - * Root type information for this type - */ + /** Root type information for this type */ rootTyping?: RootTypingDef } & AbstractTypes.MaybeTypeDefConfigFieldResolveType @@ -67,6 +59,7 @@ withNexusSymbol(NexusUnionTypeDef, NexusTypes.Union) /** * Defines a new `GraphQLUnionType` + * * @param config */ export function unionType(config: NexusUnionTypeConfig) { diff --git a/src/definitions/wrapping.ts b/src/definitions/wrapping.ts index 41a64e3e..c2168629 100644 --- a/src/definitions/wrapping.ts +++ b/src/definitions/wrapping.ts @@ -193,10 +193,7 @@ export function unwrapGraphQLDef( return { namedType, wrapping } } -/** - * Unwraps any wrapped Nexus or GraphQL types, - * turning into a list of wrapping - */ +/** Unwraps any wrapped Nexus or GraphQL types, turning into a list of wrapping */ export function unwrapNexusDef( typeDef: AllNexusTypeDefs | AllNexusArgsDefs | GraphQLType | string ): { @@ -231,10 +228,7 @@ export function unwrapNexusDef( return { namedType, wrapping } } -/** - * Takes the named type, and applies any of the NexusFinalWrapKind - * to create a properly wrapped GraphQL type. - */ +/** Takes the named type, and applies any of the NexusFinalWrapKind to create a properly wrapped GraphQL type. */ export function rewrapAsGraphQLType(baseType: GraphQLNamedType, wrapping: NexusFinalWrapKind[]): GraphQLType { let finalType: GraphQLType = baseType wrapping.forEach((wrap) => { @@ -252,7 +246,7 @@ export function rewrapAsGraphQLType(baseType: GraphQLNamedType, wrapping: NexusF /** * Apply the wrapping consistently to the arg `type` * - * nonNull(list(stringArg())) -> arg({ type: nonNull(list('String')) }) + * NonNull(list(stringArg())) -> arg({ type: nonNull(list('String')) }) */ export function normalizeArgWrapping(argVal: AllNexusArgsDefs): NexusArgDef { if (isNexusArgDef(argVal)) { @@ -271,6 +265,7 @@ export function normalizeArgWrapping(argVal: AllNexusArgsDefs): NexusArgDef = { - /** - * The name of the type this field is being declared on - */ + /** The name of the type this field is being declared on */ typeName: string stage: 'walk' | 'build' args: any[] builder: PluginBuilderLens typeDef: OutputDefinitionBlock - /** - * The list of chained wrapping calls leading up to this dynamic method - */ + /** The list of chained wrapping calls leading up to this dynamic method */ wrapping?: NexusWrapKind[] } @@ -22,45 +18,28 @@ export type InputFactoryConfig = { args: any[] builder: PluginBuilderLens typeDef: InputDefinitionBlock - /** - * The name of the type this field is being declared on - */ + /** The name of the type this field is being declared on */ typeName: string - /** - * The list of chained wrapping calls leading up to this dynamic method - */ + /** The list of chained wrapping calls leading up to this dynamic method */ wrapping?: NexusWrapKind[] } export interface BaseExtensionConfig { - /** - * The name of the "extension", the field made - * available on the builders - */ + /** The name of the "extension", the field made available on the builders */ name: T - /** - * The full type definition for the options, including generic - * signature for the type - */ + /** The full type definition for the options, including generic signature for the type */ typeDefinition?: string - /** - * Description inserted above the typeDefinition for the field, will be formatted - * as JSDOC by Nexus - */ + /** Description inserted above the typeDefinition for the field, will be formatted as JSDOC by Nexus */ typeDescription?: string } export interface DynamicOutputMethodConfig extends BaseExtensionConfig { - /** - * Invoked when the field is called - */ + /** Invoked when the field is called */ factory(config: OutputFactoryConfig): any } export interface DynamicInputMethodConfig extends BaseExtensionConfig { - /** - * Invoked when the field is called - */ + /** Invoked when the field is called */ factory(config: InputFactoryConfig): any } @@ -81,28 +60,18 @@ export class DynamicOutputMethodDef { withNexusSymbol(DynamicOutputMethodDef, NexusTypes.DynamicOutputMethod) /** - * Defines a new property on the object definition block - * for an output type, taking arbitrary input to define + * Defines a new property on the object definition block for an output type, taking arbitrary input to define * additional types. See the connectionPlugin: * - * t.connectionField('posts', { - * nullable: true, - * totalCount(root, args, ctx, info) { - * return ctx.user.getTotalPostCount(root.id, args) - * }, - * nodes(root, args, ctx, info) { - * return ctx.user.getPosts(root.id, args) - * } - * }) + * T.connectionField('posts', { nullable: true, totalCount(root, args, ctx, info) { + * return ctx.user.getTotalPostCount(root.id, args) }, nodes(root, args, ctx, info) { + * return ctx.user.getPosts(root.id, args) } }) */ export function dynamicOutputMethod(config: DynamicOutputMethodConfig) { return new DynamicOutputMethodDef(config.name, config) } -/** - * Same as the outputFieldExtension, but for fields that - * should be added on as input types. - */ +/** Same as the outputFieldExtension, but for fields that should be added on as input types. */ export function dynamicInputMethod(config: DynamicInputMethodConfig) { return new DynamicInputMethodDef(config.name, config) } diff --git a/src/dynamicProperty.ts b/src/dynamicProperty.ts index 31d27dce..b5c7bb1d 100644 --- a/src/dynamicProperty.ts +++ b/src/dynamicProperty.ts @@ -7,16 +7,12 @@ export type OutputPropertyFactoryConfig = { stage: 'walk' | 'build' builder: SchemaBuilder typeDef: OutputDefinitionBlock - /** - * The name of the type this field is being declared on - */ + /** The name of the type this field is being declared on */ typeName: string } export interface DynamicOutputPropertyConfig extends BaseExtensionConfig { - /** - * Invoked when the property is accessed (as a getter) - */ + /** Invoked when the property is accessed (as a getter) */ factory(config: OutputPropertyFactoryConfig): any } @@ -29,11 +25,10 @@ export class DynamicOutputPropertyDef { withNexusSymbol(DynamicOutputPropertyDef, NexusTypes.DynamicOutputProperty) /** - * Defines a new property on the object definition block - * for an output type, making it possible to build custom DSL's - * on top of Nexus, e.g. in nexus-prisma + * Defines a new property on the object definition block for an output type, making it possible to build + * custom DSL's on top of Nexus, e.g. in nexus-prisma * - * t.model.posts() + * T.model.posts() */ export function dynamicOutputProperty(config: DynamicOutputPropertyConfig) { return new DynamicOutputPropertyDef(config.name, config) diff --git a/src/extensions.ts b/src/extensions.ts index 00f8fe15..a831d88e 100644 --- a/src/extensions.ts +++ b/src/extensions.ts @@ -16,15 +16,10 @@ export type NexusGraphQLNamedType = GraphQLNamedType & { export type NexusTypeExtensions = NexusObjectTypeExtension | NexusInterfaceTypeExtension -/** - * Container object living on `fieldDefinition.extensions.nexus` - */ +/** Container object living on `fieldDefinition.extensions.nexus` */ export class NexusFieldExtension { readonly config: Omit, 'resolve'> - /** - * Whether the user has provided a custom "resolve" function, - * or whether we're using GraphQL's defaultResolver - */ + /** Whether the user has provided a custom "resolve" function, or whether we're using GraphQL's defaultResolver */ readonly hasDefinedResolver: boolean constructor(config: NexusOutputFieldConfig) { const { resolve, ...rest } = config @@ -33,9 +28,7 @@ export class NexusFieldExtension { readonly config: Omit, 'definition'> constructor(config: NexusInputObjectTypeConfig) { @@ -44,9 +37,7 @@ export class NexusInputObjectTypeExtension { } } -/** - * Container object living on `objectType.extensions.nexus` - */ +/** Container object living on `objectType.extensions.nexus` */ export class NexusObjectTypeExtension { readonly config: Omit, 'definition' | 'isTypeOf'> constructor(config: NexusObjectTypeConfig) { @@ -55,9 +46,7 @@ export class NexusObjectTypeExtension { } } -/** - * Container object living on `interfaceType.extensions.nexus` - */ +/** Container object living on `interfaceType.extensions.nexus` */ export class NexusInterfaceTypeExtension { readonly config: Omit, 'definition' | 'resolveType'> constructor(config: NexusInterfaceTypeConfig) { @@ -72,8 +61,8 @@ export interface NexusSchemaExtensionConfig extends Omit } /** - * Container object living on `schema.extensions.nexus`. Keeps track - * of metadata from the builder so we can use it when we + * Container object living on `schema.extensions.nexus`. Keeps track of metadata from the builder so we can + * use it when we */ export class NexusSchemaExtension { constructor(readonly config: NexusSchemaExtensionConfig) {} diff --git a/src/plugin.ts b/src/plugin.ts index e51ba3ad..2b470716 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -19,21 +19,13 @@ import { NexusFinalArgConfig } from './definitions/args' export { PluginBuilderLens } export type CreateFieldResolverInfo = { - /** - * The internal Nexus "builder" object - */ + /** The internal Nexus "builder" object */ builder: PluginBuilderLens - /** - * Info about the GraphQL Field we're decorating. - * Always guaranteed to exist, even for non-Nexus GraphQL types - */ + /** Info about the GraphQL Field we're decorating. Always guaranteed to exist, even for non-Nexus GraphQL types */ fieldConfig: Omit & { extensions?: Maybe<{ nexus?: { config: FieldExt } }> } - /** - * The config provided to the Nexus type containing the field. - * Will not exist if this is a non-Nexus GraphQL type. - */ + /** The config provided to the Nexus type containing the field. Will not exist if this is a non-Nexus GraphQL type. */ parentTypeConfig: ( | Omit | (Omit & { @@ -42,123 +34,93 @@ export type CreateFieldResolverInfo = { ) & { extensions?: Maybe<{ nexus?: { config: TypeExt } }> } - /** - * The root-level SchemaConfig passed - */ + /** The root-level SchemaConfig passed */ schemaConfig: Omit - /** - * Nexus specific metadata provided to the schema. - */ + /** Nexus specific metadata provided to the schema. */ schemaExtension: NexusSchemaExtension } export type StringLike = PrintedGenTypingImport | PrintedGenTyping | string export interface PluginConfig { - /** - * A name for the plugin, useful for errors, etc. - */ + /** A name for the plugin, useful for errors, etc. */ name: string - /** - * A description for the plugin - */ + /** A description for the plugin */ description?: string - /** - * Any type definitions we want to add to output field definitions - */ + /** Any type definitions we want to add to output field definitions */ fieldDefTypes?: StringLike | StringLike[] - /** - * Any type definitions we want to add to input field definitions - */ + /** Any type definitions we want to add to input field definitions */ inputFieldDefTypes?: StringLike | StringLike[] - /** - * Any type definitions we want to add to the type definition option - */ + /** Any type definitions we want to add to the type definition option */ objectTypeDefTypes?: StringLike | StringLike[] - /** - * Any type definitions we want to add to the arg definition option - */ + /** Any type definitions we want to add to the arg definition option */ argTypeDefTypes?: StringLike | StringLike[] /** - * Executed once, just before the types are walked. Useful for defining custom extensions - * to the "definition" builders that are needed while traversing the type definitions, as - * are defined by `dynamicOutput{Method,Property}` / `dynamicInput{Method,Property}` + * Executed once, just before the types are walked. Useful for defining custom extensions to the + * "definition" builders that are needed while traversing the type definitions, as are defined by + * `dynamicOutput{Method,Property}` / `dynamicInput{Method,Property}` */ /** - * Existing Description: - * The plugin callback to execute when onInstall lifecycle event occurs. - * OnInstall event occurs before type walking which means inline types are not - * visible at this point yet. `builderLens.hasType` will only return true - * for types the user has defined top level in their app, and any types added by - * upstream plugins. + * Existing Description: The plugin callback to execute when onInstall lifecycle event occurs. OnInstall + * event occurs before type walking which means inline types are not visible at this point yet. + * `builderLens.hasType` will only return true for types the user has defined top level in their app, and + * any types added by upstream plugins. */ onInstall?: (builder: PluginBuilderLens) => void /** - * Executed once, just after types have been walked but also before the schema definition - * types are materialized into GraphQL types. Use this opportunity to add / modify / remove - * any types before we go through the resolution step. + * Executed once, just after types have been walked but also before the schema definition types are + * materialized into GraphQL types. Use this opportunity to add / modify / remove any types before we go + * through the resolution step. */ onBeforeBuild?: (builder: PluginBuilderLens) => void - /** - * After the schema is built, provided the Schema to do any final config validation. - */ + /** After the schema is built, provided the Schema to do any final config validation. */ onAfterBuild?: (schema: GraphQLSchema) => void - /** - * Called when the `.addField` is called internally in the builder, before constructing the field - */ + /** Called when the `.addField` is called internally in the builder, before constructing the field */ onAddOutputField?: (field: NexusOutputFieldDef) => NexusOutputFieldDef | void - /** - * Called when the `.addField` is called internally in the builder, before constructing the field - */ + /** Called when the `.addField` is called internally in the builder, before constructing the field */ onAddInputField?: (field: NexusInputFieldDef) => NexusInputFieldDef | void - /** - * Called just before a Nexus arg is constructed into an GraphQLArgumentConfig - */ + /** Called just before a Nexus arg is constructed into an GraphQLArgumentConfig */ onAddArg?: (arg: NexusFinalArgConfig) => NexusFinalArgConfig | void - /** - * Called immediately after the object is defined, allows for using metadata - * to define the shape of the object. - */ + /** Called immediately after the object is defined, allows for using metadata to define the shape of the object. */ onObjectDefinition?: ( block: ObjectDefinitionBlock, objectConfig: NexusObjectTypeConfig ) => void /** - * Called immediately after the input object is defined, allows for using metadata - * to define the shape of the input object + * Called immediately after the input object is defined, allows for using metadata to define the shape of + * the input object */ onInputObjectDefinition?: ( block: InputDefinitionBlock, objectConfig: NexusInputObjectTypeConfig ) => void /** - * If a type is not defined in the schema, our plugins can register an `onMissingType` handler, - * which will intercept the missing type name and give us an opportunity to respond with a valid - * type. + * If a type is not defined in the schema, our plugins can register an `onMissingType` handler, which will + * intercept the missing type name and give us an opportunity to respond with a valid type. */ onMissingType?: (missingTypeName: string, builder: PluginBuilderLens) => any /** - * Executed any time a field resolver is created. Returning a function here will add its in the - * stack of middlewares with the (root, args, ctx, info, next) signature, where the `next` is the - * next middleware or resolver to be executed. + * Executed any time a field resolver is created. Returning a function here will add its in the stack of + * middlewares with the (root, args, ctx, info, next) signature, where the `next` is the next middleware or + * resolver to be executed. */ onCreateFieldResolver?: (createResolverInfo: CreateFieldResolverInfo) => MiddlewareFn | undefined /** - * Executed any time a "subscribe" handler is created. Returning a function here will add its in the - * stack of middlewares with the (root, args, ctx, info, next) signature, where the `next` is the - * next middleware or resolver to be executed. + * Executed any time a "subscribe" handler is created. Returning a function here will add its in the stack + * of middlewares with the (root, args, ctx, info, next) signature, where the `next` is the next middleware + * or resolver to be executed. */ onCreateFieldSubscribe?: (createSubscribeInfo: CreateFieldResolverInfo) => MiddlewareFn | undefined /** - * Executed when a field is going to be printed to the nexus "generated types". Gives - * an opportunity to override the standard behavior for printing our inferrred type info + * Executed when a field is going to be printed to the nexus "generated types". Gives an opportunity to + * override the standard behavior for printing our inferrred type info */ // onPrint?: (visitor: Visitor) => void; } /** - * Helper for allowing plugins to fulfill the return of the `next` resolver, - * without paying the cost of the Promise if not required. + * Helper for allowing plugins to fulfill the return of the `next` resolver, without paying the cost of the + * Promise if not required. */ export function completeValue( valOrPromise: PromiseLike | T, @@ -183,8 +145,8 @@ export type MiddlewareFn = ( ) => any /** - * Takes a list of middlewares and executes them sequentially, passing the - * "next" member of the chain to execute as the 5th arg. + * Takes a list of middlewares and executes them sequentially, passing the "next" member of the chain to + * execute as the 5th arg. * * @param middleware * @param resolver @@ -204,28 +166,23 @@ export function composeMiddlewareFns( return lastResolver } -/** - * A definition for a plugin. Should be passed to the `plugins: []` option - * on makeSchema - */ +/** A definition for a plugin. Should be passed to the `plugins: []` option on makeSchema */ export class NexusPlugin { constructor(readonly config: PluginConfig) {} } withNexusSymbol(NexusPlugin, NexusTypes.Plugin) /** - * A plugin defines configuration which can document additional metadata options - * for a type definition. This metadata can be used to decorate the "resolve" function - * to provide custom functionality, such as logging, error handling, additional type - * validation. + * A plugin defines configuration which can document additional metadata options for a type definition. This + * metadata can be used to decorate the "resolve" function to provide custom functionality, such as logging, + * error handling, additional type validation. * - * You can specify options which can be defined on the schema, - * the type or the plugin. The config from each of these will be - * passed in during schema construction time, and used to augment the field as necessary. + * You can specify options which can be defined on the schema, the type or the plugin. The config from each of + * these will be passed in during schema construction time, and used to augment the field as necessary. * - * You can either return a function, with the new defintion of a resolver implementation, - * or you can return an "enter" / "leave" pairing which will wrap the pre-execution of the - * resolver and the "result" of the resolver, respectively. + * You can either return a function, with the new defintion of a resolver implementation, or you can return an + * "enter" / "leave" pairing which will wrap the pre-execution of the resolver and the "result" of the + * resolver, respectively. */ export function plugin(config: PluginConfig) { validatePluginConfig(config) @@ -236,9 +193,7 @@ plugin.completeValue = completeValue // For backward compat export const createPlugin = plugin -/** - * Validate that the configuration given by a plugin is valid. - */ +/** Validate that the configuration given by a plugin is valid. */ function validatePluginConfig(pluginConfig: PluginConfig): void { const validRequiredProps = ['name'] const optionalPropFns: Array = [ diff --git a/src/plugins/connectionPlugin.ts b/src/plugins/connectionPlugin.ts index 3e3f27a6..c0a2abd7 100644 --- a/src/plugins/connectionPlugin.ts +++ b/src/plugins/connectionPlugin.ts @@ -37,8 +37,7 @@ export interface ConnectionPluginConfig { */ includeNodesField?: boolean /** - * Any args to include by default on all connection fields, - * in addition to the ones in the spec. + * Any args to include by default on all connection fields, in addition to the ones in the spec. * * @default null */ @@ -58,14 +57,14 @@ export interface ConnectionPluginConfig { /** * Custom logic to validate the arguments. * - * Defaults to requiring that either a `first` or `last` is provided, and - * that after / before must be paired with `first` or `last`, respectively. + * Defaults to requiring that either a `first` or `last` is provided, and that after / before must be paired + * with `first` or `last`, respectively. */ validateArgs?: (args: Record, info: GraphQLResolveInfo) => void /** - * If disableForwardPagination or disableBackwardPagination are set to true, - * we require the `first` or `last` field as needed. Defaults to true, - * setting this to false will disable this behavior and make the field nullable. + * If disableForwardPagination or disableBackwardPagination are set to true, we require the `first` or + * `last` field as needed. Defaults to true, setting this to false will disable this behavior and make the + * field nullable. */ strictArgs?: boolean /** @@ -73,7 +72,7 @@ export interface ConnectionPluginConfig { * * Default is `cursor:${index}` * - * @default "field" + * @default field */ cursorFromNode?: ( node: any, @@ -83,8 +82,8 @@ export interface ConnectionPluginConfig { forCursor: { index: number; nodes: any[] } ) => string | Promise /** - * Override the default behavior of determining hasNextPage / hasPreviousPage. Usually needed - * when customizing the behavior of `cursorFromNode` + * Override the default behavior of determining hasNextPage / hasPreviousPage. Usually needed when + * customizing the behavior of `cursorFromNode` */ pageInfoFromNodes?: ( allNodes: any[], @@ -92,67 +91,53 @@ export interface ConnectionPluginConfig { ctx: GetGen<'context'>, info: GraphQLResolveInfo ) => MaybePromise<{ hasNextPage: boolean; hasPreviousPage: boolean }> - /** - * Conversion from a cursor string into an opaque token. Defaults to base64Encode(string) - */ + /** Conversion from a cursor string into an opaque token. Defaults to base64Encode(string) */ encodeCursor?: (value: string) => string - /** - * Conversion from an opaque token into a cursor string. Defaults to base64Decode(string) - */ + /** Conversion from an opaque token into a cursor string. Defaults to base64Decode(string) */ decodeCursor?: (cursor: string) => string - /** - * Extend *all* edges to include additional fields, beyond cursor and node - */ + /** Extend *all* edges to include additional fields, beyond cursor and node */ extendEdge?: Record< string, Omit, 'resolve'> & { /** - * Set requireResolver to false if you have already resolved this information during the resolve - * of the edges in the parent resolve method + * Set requireResolver to false if you have already resolved this information during the resolve of the + * edges in the parent resolve method + * * @default true */ requireResolver?: boolean } > - /** - * Any additional fields to make available to the connection type, - * beyond edges, pageInfo - */ + /** Any additional fields to make available to the connection type, beyond edges, pageInfo */ extendConnection?: Record< string, Omit, 'resolve'> & { /** - * Set requireResolver to false if you have already resolved this information during the resolve - * of the edges in the parent resolve method + * Set requireResolver to false if you have already resolved this information during the resolve of the + * edges in the parent resolve method + * * @default true */ requireResolver?: boolean } > - /** - * Prefix for the Connection / Edge type - */ + /** Prefix for the Connection / Edge type */ typePrefix?: string /** - * The path to the @nexus/schema package. Needed for typegen. + * The path to the @nexus/schema package for typegen. * - * @default '@nexus/schema' - * - * @remarks + * This setting is only necessary when @nexus/schema is being wrapped by another library/framework such that + * `@nexus/schema` is not expected to be a direct dependency at the application level. * - * This setting is particularly useful when @nexus/schema is being wrapped by - * another library/framework such that @nexus/schema is not expected to be a - * direct dependency at the application level. + * @default '@nexus/schema' */ nexusSchemaImportId?: string /** - * Configures the default "nonNullDefaults" settings for any connection types - * created globally by this config / connection field. + * Configures the default "nonNullDefaults" settings for any connection types created globally by this + * config / connection field. */ nonNullDefaults?: NonNullConfig - /** - * Allows specifying a custom cursor type, as the name of a scalar - */ + /** Allows specifying a custom cursor type, as the name of a scalar */ cursorType?: | GetGen<'scalarNames'> | NexusNullDef> @@ -169,12 +154,11 @@ export type ConnectionFieldConfig | AllNexusNamedOutputTypeDefs /** * Whether the connection field can be null + * * @default (depends on whether nullability is configured in type or schema) */ nullable?: boolean - /** - * Additional args to use for just this field - */ + /** Additional args to use for just this field */ additionalArgs?: ArgsRecord /** * Whether to inherit "additional args" if they exist on the plugin definition @@ -185,7 +169,7 @@ export type ConnectionFieldConfig, @@ -195,8 +179,8 @@ export type ConnectionFieldConfig[] } ) => string | Promise /** - * Override the default behavior of determining hasNextPage / hasPreviousPage. Usually needed - * when customizing the behavior of `cursorFromNode` + * Override the default behavior of determining hasNextPage / hasPreviousPage. Usually needed when + * customizing the behavior of `cursorFromNode` */ pageInfoFromNodes?: ( nodes: NodeValue[], @@ -204,62 +188,50 @@ export type ConnectionFieldConfig, info: GraphQLResolveInfo ) => MaybePromise<{ hasNextPage: boolean; hasPreviousPage: boolean }> - /** - * Whether the field allows for backward pagination - */ + /** Whether the field allows for backward pagination */ disableForwardPagination?: boolean - /** - * Whether the field allows for backward pagination - */ + /** Whether the field allows for backward pagination */ disableBackwardPagination?: boolean /** - * If disableForwardPagination or disableBackwardPagination are set to true, - * we require the `first` or `last` field as needed. Defaults to true, - * setting this to false will disable this behavior and make the field nullable. + * If disableForwardPagination or disableBackwardPagination are set to true, we require the `first` or + * `last` field as needed. Defaults to true, setting this to false will disable this behavior and make the + * field nullable. */ strictArgs?: boolean /** * Custom logic to validate the arguments. * - * Defaults to requiring that either a `first` or `last` is provided, and - * that after / before must be paired with `first` or `last`, respectively. + * Defaults to requiring that either a `first` or `last` is provided, and that after / before must be paired + * with `first` or `last`, respectively. */ validateArgs?: (args: Record, info: GraphQLResolveInfo) => void /** - * Dynamically adds additional fields to the current "connection" when it is defined. - * This will cause the resulting type to be prefix'ed with the name of the type/field it is branched off of, - * so as not to conflict with any non-extended connections. + * Dynamically adds additional fields to the current "connection" when it is defined. This will cause the + * resulting type to be prefix'ed with the name of the type/field it is branched off of, so as not to + * conflict with any non-extended connections. */ extendConnection?: (def: ObjectDefinitionBlock>) => void /** - * Dynamically adds additional fields to the connection "edge" when it is defined. - * This will cause the resulting type to be prefix'ed with the name of the type/field it is branched off of, - * so as not to conflict with any non-extended connections. + * Dynamically adds additional fields to the connection "edge" when it is defined. This will cause the + * resulting type to be prefix'ed with the name of the type/field it is branched off of, so as not to + * conflict with any non-extended connections. */ extendEdge?: ( def: ObjectDefinitionBlock, 'edges'>> ) => void - /** - * Configures the default "nonNullDefaults" for connection type generated - * for this connection - */ + /** Configures the default "nonNullDefaults" for connection type generated for this connection */ nonNullDefaults?: NonNullConfig - /** - * Allows specifying a custom cursor type, as the name of a scalar - */ + /** Allows specifying a custom cursor type, as the name of a scalar */ cursorType?: | GetGen<'scalarNames'> | NexusNullDef> | NexusNonNullDef> - /** - * Defined if you have extended the connectionPlugin globally - */ + /** Defined if you have extended the connectionPlugin globally */ edgeFields?: unknown } & ( | { /** - * Nodes should resolve to an Array, with a length of one greater than the direction you - * are paginating. + * Nodes should resolve to an Array, with a length of one greater than the direction you are paginating. * * For example, if you're paginating forward, and assuming an Array with length 20: * @@ -267,9 +239,9 @@ export type ConnectionFieldConfig= the node count. + * We will then slice the array in the direction we're iterating, and if there are more than "N" + * results, we will assume there's a next page. If you set `assumeExactNodeCount: true` in the config, + * we will assume that a next page exists if the length >= the node count. */ nodes: ( root: RootValue, @@ -283,11 +255,11 @@ export type ConnectionFieldConfig, @@ -867,9 +839,7 @@ function defaultHasNextPage(nodes: any[], args: PaginationArgs) { throw new Error('Unreachable') } -/** - * A sensible default for determining "previous page". - */ +/** A sensible default for determining "previous page". */ function defaultHasPreviousPage(nodes: any[], args: PaginationArgs) { // If we're paginating forward, and we don't have an "after", we'll assume that we don't have // a previous page, otherwise we will assume we have one, unless the after cursor === "0". diff --git a/src/plugins/declarativeWrappingPlugin.ts b/src/plugins/declarativeWrappingPlugin.ts index ce1d2a71..d30c7922 100644 --- a/src/plugins/declarativeWrappingPlugin.ts +++ b/src/plugins/declarativeWrappingPlugin.ts @@ -53,14 +53,9 @@ Whether the type should be non null, \`required: true\` = \`nullable: false\` ] export type DeclarativeWrappingPluginConfig = { - /** - * Whether we should warn, the default when not otherwise specified. - */ + /** Whether we should warn, the default when not otherwise specified. */ shouldWarn?: boolean - /** - * Whether we should completely disable the plugin, not install types, and throw when - * we encounter any issues. - */ + /** Whether we should completely disable the plugin, not install types, and throw when we encounter any issues. */ disable?: boolean } diff --git a/src/plugins/nullabilityGuardPlugin.ts b/src/plugins/nullabilityGuardPlugin.ts index b8434daf..c425d543 100644 --- a/src/plugins/nullabilityGuardPlugin.ts +++ b/src/plugins/nullabilityGuardPlugin.ts @@ -38,19 +38,14 @@ export type NullFallbackValues = Partial< > export type NullabilityGuardConfig = { - /** - * Whether we should guard against non-null values. Defaults to "true" if NODE_ENV === "production", - * false otherwise. - */ + /** Whether we should guard against non-null values. Defaults to "true" if NODE_ENV === "production", false otherwise. */ shouldGuard?: boolean /** - * When a nullish value is "guarded", meaning it is coerced into an acceptable non-null - * value, this function will be called if supplied. + * When a nullish value is "guarded", meaning it is coerced into an acceptable non-null value, this function + * will be called if supplied. */ onGuarded?: (obj: NullabilityPluginOnGuardedConfig) => void - /** - * A mapping of typename to the value that should be used in the case of a null value. - */ + /** A mapping of typename to the value that should be used in the case of a null value. */ fallbackValues?: NullFallbackValues } diff --git a/src/sdlConverter.ts b/src/sdlConverter.ts index b960b0be..eef0865b 100644 --- a/src/sdlConverter.ts +++ b/src/sdlConverter.ts @@ -28,9 +28,7 @@ export function convertSDL(sdl: string, commonjs: null | boolean = false, json = } } -/** - * Convert an existing SDL schema into a GraphQL Nexus format - */ +/** Convert an existing SDL schema into a GraphQL Nexus format */ export class SDLConverter { protected export: string protected schema: GraphQLSchema | null diff --git a/src/typeHelpersInternal.ts b/src/typeHelpersInternal.ts index 71a11495..240c1e82 100644 --- a/src/typeHelpersInternal.ts +++ b/src/typeHelpersInternal.ts @@ -1,7 +1,4 @@ -/** - * Borrowed from `type-fest` - * Extract the keys from a type where the value type of the key extends the given `Condition`. - */ +/** Borrowed from `type-fest` Extract the keys from a type where the value type of the key extends the given `Condition`. */ export type ConditionalKeys = NonNullable< // Wrap in `NonNullable` to strip away the `undefined` type from the produced union. { @@ -14,21 +11,13 @@ export type ConditionalKeys = NonNullable< }[keyof Base] > -/** - * Taken from `type-fest` - * Pick keys from the shape that matches the given `Condition`. - */ +/** Taken from `type-fest` Pick keys from the shape that matches the given `Condition`. */ export type ConditionalPick = Pick> -/** - * Taken from `type-fest` - * Get the values of a mapped types - */ +/** Taken from `type-fest` Get the values of a mapped types */ export type ValueOf = ObjectType[ValueType] -/** - * Is the given type equal to the other given type? - */ +/** Is the given type equal to the other given type? */ export type IsEqual = A extends B ? (B extends A ? true : false) : false export type RequiredDeeply = DoRequireDeeply> @@ -37,16 +26,13 @@ export type RequiredDeeply = DoRequireDeeply> * Represents a POJO. Prevents from allowing arrays and functions. * * @remarks - * - * TypeScript interfaces will not be considered sub-types. + * TypeScript interfaces will not be considered sub-types. */ export type PlainObject = { [x: string]: Primitive | object } -/** - * Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). - */ +/** Matches any [primitive value](https://developer.mozilla.org/en-US/docs/Glossary/Primitive). */ export type Primitive = null | undefined | string | number | boolean | symbol | bigint type DoRequireDeeply = { diff --git a/src/typegenAbstractTypes.ts b/src/typegenAbstractTypes.ts index 26becbc8..0eb12f52 100644 --- a/src/typegenAbstractTypes.ts +++ b/src/typegenAbstractTypes.ts @@ -13,9 +13,8 @@ import { ConditionalKeys, ConditionalPick, ValueOf } from './typeHelpersInternal * Returns a union of all the type names of the members of an abstract type * * @example - * - * union D = A | B | C - * PossibleTypeNames<'D> // 'A' | 'B' | 'C' + * union D = A | B | C + * PossibleTypeNames<'D> // 'A' | 'B' | 'C' */ export type PossibleTypeNames = ValueOf< ConditionalPick, AbstractTypeName> @@ -24,8 +23,8 @@ export type PossibleTypeNames = ValueOf< * Returns a union of all the members of an abstract type * * @example - * union D = A | B | C - * PossibleTypes<'D> // A | B | C + * union D = A | B | C + * PossibleTypes<'D> // A | B | C */ export type PossibleTypes = RootValue> @@ -33,27 +32,23 @@ export type PossibleTypes = RootValue // 'D' | 'E' + * union D = A | B + * union E = A + * AbstractTypeNames<'A'> // 'D' | 'E' */ export type AbstractTypeNames = ConditionalKeys< GetGen<'abstractTypeMembers'>, TypeName > -/** - * Returns whether all the abstract type names where TypeName is used have implemented `resolveType` - */ +/** Returns whether all the abstract type names where TypeName is used have implemented `resolveType` */ export type IsStrategyResolveTypeImplementedInAllAbstractTypes = AbstractTypeNames< TypeName > extends GetGen<'abstractsUsingStrategyResolveType'> ? true : false -/** - * Returns whether all the members of an abstract type have implemented `isTypeOf` - */ +/** Returns whether all the members of an abstract type have implemented `isTypeOf` */ export type IsStrategyIsTypeOfImplementedInAllMembers = GetGen2< 'abstractTypeMembers', AbstractTypeName @@ -71,8 +66,7 @@ export type IsTypeOfHandler = ( * Get an object with the `isTypeOf` field if applicable for the given object Type. * * @remarks - * - * Intersect the result of this with other things to build up the final options for a type def. + * Intersect the result of this with other things to build up the final options for a type def. */ // prettier-ignore export type MaybeTypeDefConfigFieldIsTypeOf = @@ -90,8 +84,7 @@ IsFeatureEnabled2<'abstractTypeStrategies', 'isTypeOf'> extends false // is isTy * Get an object with the `resolveType` field if applicable for the given abstract Type. * * @remarks - * - * Intersect the result of this with other things to build up the final options for a type def. + * Intersect the result of this with other things to build up the final options for a type def. */ export type MaybeTypeDefConfigFieldResolveType = IsFeatureEnabled2< 'abstractTypeStrategies', @@ -101,26 +94,23 @@ export type MaybeTypeDefConfigFieldResolveType = IsFeat : IsStrategyIsTypeOfImplementedInAllMembers extends true ? { /** - * Optionally provide a custom type resolver function. If one is not provided, - * the default implementation will call `isTypeOf` on each implementing - * Object type. + * Optionally provide a custom type resolver function. If one is not provided, the default + * implementation will call `isTypeOf` on each implementing Object type. */ resolveType?: AbstractTypeResolver } // Make resolveType optional when __typename strategy is enabled : IsFeatureEnabled2<'abstractTypeStrategies', '__typename'> extends true ? { /** - * Optionally provide a custom type resolver function. If one is not provided, - * the default implementation will call `isTypeOf` on each implementing - * Object type. + * Optionally provide a custom type resolver function. If one is not provided, the default + * implementation will call `isTypeOf` on each implementing Object type. */ resolveType?: AbstractTypeResolver } : { /** - * Optionally provide a custom type resolver function. If one is not provided, - * the default implementation will call `isTypeOf` on each implementing - * Object type. + * Optionally provide a custom type resolver function. If one is not provided, the default + * implementation will call `isTypeOf` on each implementing Object type. */ resolveType: AbstractTypeResolver } diff --git a/src/typegenAutoConfig.ts b/src/typegenAutoConfig.ts index 082efcd8..7ad6e246 100644 --- a/src/typegenAutoConfig.ts +++ b/src/typegenAutoConfig.ts @@ -5,9 +5,7 @@ import { RootTypingDef, TypingImport } from './definitions/_types' import { TYPEGEN_HEADER } from './lang' import { getOwnPackage, log, objValues, relativePathTo, typeScriptFileExtension } from './utils' -/** - * Any common types / constants that would otherwise be circular-imported - */ +/** Any common types / constants that would otherwise be circular-imported */ export const SCALAR_TYPES = { Int: 'number', String: 'string', @@ -18,16 +16,14 @@ export const SCALAR_TYPES = { export interface TypegenConfigSourceModule { /** - * The module for where to look for the types. - * This uses the node resolution algorithm via require.resolve, - * so if this lives in node_modules, you can just provide the module name - * otherwise you should provide the absolute path to the file. + * The module for where to look for the types. This uses the node resolution algorithm via require.resolve, + * so if this lives in node_modules, you can just provide the module name otherwise you should provide the + * absolute path to the file. */ source: string /** - * When we import the module, we use `import * as ____` to prevent - * conflicts. This alias should be a name that doesn't conflict with any other - * types, usually a short lowercase name. + * When we import the module, we use `import * as ____` to prevent conflicts. This alias should be a name + * that doesn't conflict with any other types, usually a short lowercase name. */ alias: string /** @@ -35,44 +31,40 @@ export interface TypegenConfigSourceModule { * * If not provided, the default implementation is: * - * (type) => [ - * new RegExp(`(?:interface|type|class|enum)\\s+(${type.name})\\W`, "g"), - * ] - * + * (type) => [ + * new RegExp(`(?:interface|type|class|enum)\\s+(${type.name})\\W`, "g"), ] */ typeMatch?: (type: GraphQLNamedType, defaultRegex: RegExp) => RegExp | RegExp[] /** - * A list of typesNames or regular expressions matching type names - * that should be resolved by this import. Provide an empty array if you - * wish to use the file for context and ensure no other types are matched. + * A list of typesNames or regular expressions matching type names that should be resolved by this import. + * Provide an empty array if you wish to use the file for context and ensure no other types are matched. */ onlyTypes?: (string | RegExp)[] /** - * By default the import is configured `import * as alias from`, setting glob to false - * will change this to `import alias from` + * By default the import is configured `import * as alias from`, setting glob to false will change this to + * `import alias from` */ glob?: false } export interface TypegenAutoConfigOptions { - /** - * Any headers to prefix on the generated type file - */ + /** Any headers to prefix on the generated type file */ headers?: string[] /** * Array of TypegenConfigSourceModule's to look in and match the type names against. * - * ``` - * sources: [ - * { source: 'typescript', alias: 'ts' }, - * { source: path.join(__dirname, '../backingTypes'), alias: 'b' }, - * ] - * ``` + * @example + * sources: [ + * { source: 'typescript', alias: 'ts' }, + * { source: path.join(__dirname, '../backingTypes'), alias: 'b' }, + * ] */ sources: TypegenConfigSourceModule[] /** - * Typing for the context, referencing a type defined in the aliased module - * provided in sources e.g. `alias.Context` + * Typing for the context, referencing a type defined in the aliased module provided in sources e.g. `alias.Context` + * + * @example + * contextType: 't.Context' */ contextType?: RootTypingDef /** @@ -80,32 +72,28 @@ export interface TypegenAutoConfigOptions { * * By default this is set to ['Query', 'Mutation', 'Subscription'] * - * ``` - * skipTypes: ['Query', 'Mutation', /(.*?)Edge/, /(.*?)Connection/] - * ``` + * @example + * skipTypes: ['Query', 'Mutation', /(.*?)Edge/, /(.*?)Connection/] */ skipTypes?: (string | RegExp)[] /** - * If debug is set to true, this will log out info about all types - * found, skipped, etc. for the type generation files. + * If debug is set to true, this will log out info about all types found, skipped, etc. for the type + * generation files. @default false */ debug?: boolean /** - * If provided this will be used for the backing types rather than the auto-resolve - * mechanism above. Useful as an override for one-off cases, or for scalar - * backing types. + * If provided this will be used for the backing types rather than the auto-resolve mechanism above. Useful + * as an override for one-off cases, or for scalar backing types. */ backingTypeMap?: Record } /** - * This is an approach for handling type definition auto-resolution. - * It is designed to handle the most common cases, as can be seen - * in the examples / the simplicity of the implementation. + * This is an approach for handling type definition auto-resolution. It is designed to handle the most common + * cases, as can be seen in the examples / the simplicity of the implementation. * - * If you wish to do something more complex, involving full - * AST parsing, etc, you can provide a different function to - * the `typegenInfo` property of the `makeSchema` config. + * If you wish to do something more complex, involving full AST parsing, etc, you can provide a different + * function to the `typegenInfo` property of the `makeSchema` config. * * @param options */ diff --git a/src/typegenMetadata.ts b/src/typegenMetadata.ts index d0ae289f..64a073bb 100644 --- a/src/typegenMetadata.ts +++ b/src/typegenMetadata.ts @@ -17,17 +17,13 @@ export interface TypegenMetadataConfig } /** - * Passed into the SchemaBuilder, this keeps track of any necessary - * field / type metadata we need to be aware of when building the - * generated types and/or SDL artifact, including but not limited to: + * Passed into the SchemaBuilder, this keeps track of any necessary field / type metadata we need to be aware + * of when building the generated types and/or SDL artifact, including but not limited to: */ export class TypegenMetadata { constructor(protected config: TypegenMetadataConfig) {} - /** - * Generates the artifacts of the build based on what we - * know about the schema and how it was defined. - */ + /** Generates the artifacts of the build based on what we know about the schema and how it was defined. */ async generateArtifacts(schema: NexusGraphQLSchema) { const sortedSchema = this.sortSchema(schema) if (this.config.outputs.schema || this.config.outputs.typegen) { @@ -106,9 +102,7 @@ export class TypegenMetadata { } } - /** - * Generates the schema, adding any directives as necessary - */ + /** Generates the schema, adding any directives as necessary */ generateSchemaFile(schema: GraphQLSchema): string { let printedSchema = this.config.customPrintSchemaFn ? this.config.customPrintSchemaFn(schema) @@ -116,9 +110,7 @@ export class TypegenMetadata { return [SDL_HEADER, printedSchema].join('\n\n') } - /** - * Generates the type definitions - */ + /** Generates the type definitions */ async generateTypesFile(schema: NexusGraphQLSchema, typegenFile: string): Promise { return new TypegenPrinter(schema, { ...(await this.getTypegenInfo(schema)), diff --git a/src/typegenPrinter.ts b/src/typegenPrinter.ts index 2522a365..05c8e532 100644 --- a/src/typegenPrinter.ts +++ b/src/typegenPrinter.ts @@ -58,12 +58,12 @@ interface TypegenInfoWithFile extends TypegenInfo { * We track and output a few main things: * * 1. "root" types, or the values that fill the first - * argument for a given object type + * argument for a given object type * * 2. "arg" types, the values that are arguments to output fields. * * 3. "return" types, the values returned from the resolvers... usually - * just list/nullable variations on the "root" types for other types + * just list/nullable variations on the "root" types for other types * * 4. The names of all types, grouped by type. * diff --git a/src/typegenTypeHelpers.spec.types.ts b/src/typegenTypeHelpers.spec.types.ts index d39a0de2..98af60af 100644 --- a/src/typegenTypeHelpers.spec.types.ts +++ b/src/typegenTypeHelpers.spec.types.ts @@ -1,9 +1,7 @@ import { expectAssignable } from 'tsd' import { MaybePromiseDeep } from './typegenTypeHelpers' -/** - * MaybePromiseDeep - */ +/** MaybePromiseDeep */ // A case found by Sytten https://github.com/graphql-nexus/schema/issues/470 // The presence of .then was leading to type errors diff --git a/src/typegenTypeHelpers.ts b/src/typegenTypeHelpers.ts index c13f2ae6..c61dd3f5 100644 --- a/src/typegenTypeHelpers.ts +++ b/src/typegenTypeHelpers.ts @@ -18,10 +18,7 @@ export type AllInputTypes = GetGen<'allInputTypes', string> export type AllOutputTypes = GetGen<'allOutputTypes', string> -/** - * This type captures all output types defined in the app - * as well as core GraphQL spec objects. - */ +/** This type captures all output types defined in the app as well as core GraphQL spec objects. */ export type AllOutputTypesPossible = AllOutputTypes | 'Query' | 'Mutation' | 'Subscription' export type FieldType = GetGen3< @@ -33,9 +30,8 @@ export type FieldType = GetGe export type MaybePromise = PromiseLike | T /** - * Because the GraphQL field execution algorithm automatically - * resolves promises at any level of the tree, we use this - * to help signify that. + * Because the GraphQL field execution algorithm automatically resolves promises at any level of the tree, we + * use this to help signify that. */ export type MaybePromiseDeep = Date extends T ? MaybePromise @@ -61,19 +57,16 @@ export type MaybePromiseDeep = Date extends T : MaybePromise /** - * The NexusAbstractTypeResolver type can be used if you want to preserve type-safety - * and autocomplete on an abstract type resolver (interface or union) outside of the Nexus - * configuration + * The NexusAbstractTypeResolver type can be used if you want to preserve type-safety and autocomplete on an + * abstract type resolver (interface or union) outside of the Nexus configuration * * @example - * ``` - * const mediaType: AbstractTypeResolver<'MediaType'> = (root, ctx, info) => { - * if (ctx.user.isLoggedIn()) { - * return ctx.user.getItems() + * const mediaType: AbstractTypeResolver<'MediaType'> = (root, ctx, info) => { + * if (ctx.user.isLoggedIn()) { + * return ctx.user.getItems() + * } + * return null * } - * return null - * } - * ``` */ export interface AbstractTypeResolver { ( @@ -85,18 +78,16 @@ export interface AbstractTypeResolver { } /** - * The FieldResolver type can be used when you want to preserve type-safety - * and autocomplete on a resolver outside of the Nexus definition block + * The FieldResolver type can be used when you want to preserve type-safety and autocomplete on a resolver + * outside of the Nexus definition block * * @example - * ``` - * const userItems: FieldResolver<'User', 'items'> = (root, args, ctx, info) => { - * if (ctx.user.isLoggedIn()) { - * return ctx.user.getItems() + * const userItems: FieldResolver<'User', 'items'> = (root, args, ctx, info) => { + * if (ctx.user.isLoggedIn()) { + * return ctx.user.getItems() + * } + * return null * } - * return null - * } - * ``` */ export type FieldResolver = ( root: RootValue, @@ -126,9 +117,7 @@ export type SubFieldResolver< export type AbstractResolveReturn = GetGen2<'abstractTypeMembers', TypeName, any> -/** - * Generated type helpers: - */ +/** Generated type helpers: */ export type GenTypesShapeKeys = | 'context' | 'inputTypes' @@ -153,9 +142,7 @@ export type GenTypesShapeKeys = | 'abstractsUsingStrategyResolveType' | 'features' -/** - * Helpers for handling the generated schema - */ +/** Helpers for handling the generated schema */ export type GenTypesShape = Record export type GetGen = NexusGen extends infer GenTypes diff --git a/src/typegenUtils.ts b/src/typegenUtils.ts index 0cadd603..339f0001 100644 --- a/src/typegenUtils.ts +++ b/src/typegenUtils.ts @@ -3,9 +3,7 @@ import { BuilderConfigInput } from './builder' import { TypegenMetadataConfig } from './typegenMetadata' import { assertAbsolutePath, getOwnPackage, isProductionStage } from './utils' -/** - * Normalizes the builder config into the config we need for typegen - */ +/** Normalizes the builder config into the config we need for typegen */ export function resolveTypegenConfig(config: BuilderConfigInput): TypegenMetadataConfig { const { outputs, diff --git a/src/utils.ts b/src/utils.ts index b3d01c76..471c502f 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -47,15 +47,11 @@ export const isInterfaceField = (type: GraphQLObjectType, fieldName: string) => // ---------------------------- -/** - * - * Copied from graphql-js: - * - */ +/** Copied from graphql-js: */ /** - * Given an invalid input string and a list of valid options, returns a filtered - * list of valid options sorted based on their similarity with the input. + * Given an invalid input string and a list of valid options, returns a filtered list of valid options sorted + * based on their similarity with the input. */ export function suggestionList(input: string = '', options: string[] = []): string[] { var optionsByDistance = Object.create(null) @@ -78,14 +74,12 @@ export function suggestionList(input: string = '', options: string[] = []): stri /** * Computes the lexical distance between strings A and B. * - * The "distance" between two strings is given by counting the minimum number - * of edits needed to transform string A into string B. An edit can be an - * insertion, deletion, or substitution of a single character, or a swap of two - * adjacent characters. + * The "distance" between two strings is given by counting the minimum number of edits needed to transform + * string A into string B. An edit can be an insertion, deletion, or substitution of a single character, or a + * swap of two adjacent characters. * - * Includes a custom alteration from Damerau-Levenshtein to treat case changes - * as a single edit which helps identify mis-cased values with an edit distance - * of 1. + * Includes a custom alteration from Damerau-Levenshtein to treat case changes as a single edit which helps + * identify mis-cased values with an edit distance of 1. * * This distance can be useful for detecting typos in input or sorting */ @@ -237,11 +231,8 @@ function nixifyPathSlashes(path: string): string { /** * Format a path so it is suitable to be used as a module import. * - * - Implicitly relative is made explicitly relative - * - TypeScript file extension is stripped - * - Windows slashes converted into *nix slashes - * - * @remarks + * - Implicitly relative is made explicitly relative - TypeScript file extension is stripped - Windows slashes + * converted into *nix slashes * * Do not pass Node module IDs here as they will be treated as relative paths e.g. "react" "@types/react" etc. */ @@ -419,12 +410,12 @@ export function log(msg: string) { } /** - * Calculate the venn diagram between two iterables based on reference equality - * checks. The returned tripple contains items thusly: + * Calculate the venn diagram between two iterables based on reference equality checks. The returned tripple + * contains items thusly: * - * * items only in arg 1 --> first tripple slot - * * items in args 1 & 2 --> second tripple slot - * * items only in arg 2 --> third tripple slot + * * items only in arg 1 --> first tripple slot + * * items in args 1 & 2 --> second tripple slot + * * items only in arg 2 --> third tripple slot */ export function venn(xs: Iterable, ys: Iterable): [Set, Set, Set] { const lefts: Set = new Set(xs) @@ -479,17 +470,12 @@ export function getOwnPackage(): { name: string } { return require('../package.json') } -/** - * Use this to make assertion at end of if-else chain that all members of a - * union have been accounted for. - */ +/** Use this to make assertion at end of if-else chain that all members of a union have been accounted for. */ export function casesHandled(x: never): never { throw new Error(`A case was not handled for value: ${x}`) } -/** - * Quickly log objects - */ +/** Quickly log objects */ export function dump(x: any) { console.log(require('util').inspect(x, { depth: null })) } @@ -523,10 +509,7 @@ export function resolveImportPath(rootType: TypingImport, typeName: string, outp return importPath } -/** - * Given the right hand side of an arg definition, returns the underlying "named type" - * for us to add to the builder - */ +/** Given the right hand side of an arg definition, returns the underlying "named type" for us to add to the builder */ export function getArgNamedType(argDef: AllNexusArgsDefs | string): AllNexusNamedInputTypeDefs | string { let finalValue = argDef if (typeof finalValue === 'string') { @@ -562,9 +545,7 @@ export function getNexusNamedType( return namedType } -/** - * Assertion utility with nexus-aware feedback for users. - */ +/** Assertion utility with nexus-aware feedback for users. */ export function invariantGuard(val: any) { /* istanbul ignore next */ if (Boolean(val) === false) { @@ -575,16 +556,12 @@ export function invariantGuard(val: any) { } } -/** - * Is the current stage production? If NODE_ENV envar is set to "production" or "prod" then yes it is. - */ +/** Is the current stage production? If NODE_ENV envar is set to "production" or "prod" then yes it is. */ export function isProductionStage() { return process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'prod' } -/** - * Throw a programmer error in production but only log it in development. - */ +/** Throw a programmer error in production but only log it in development. */ export function raiseProgrammerError(error: Error) { if (isProductionStage()) { throw error diff --git a/tests/__helpers/helpers.ts b/tests/__helpers/helpers.ts index 02e02816..2960022b 100644 --- a/tests/__helpers/helpers.ts +++ b/tests/__helpers/helpers.ts @@ -1,9 +1,7 @@ import * as GQL from 'graphql' import { inputObjectType, objectType } from '../../src' -/** - * Used in testing, creates a generic "User" object - */ +/** Used in testing, creates a generic "User" object */ export const UserObject = objectType({ name: 'User', definition(t) { @@ -34,9 +32,7 @@ export const restoreEnvBeforeEach = () => { }) } -/** - * Subscription helpers - */ +/** Subscription helpers */ export function subscribe( schema: GQL.GraphQLSchema, diff --git a/tests/__helpers/testApp.ts b/tests/__helpers/testApp.ts index e52b723c..307c8bd0 100644 --- a/tests/__helpers/testApp.ts +++ b/tests/__helpers/testApp.ts @@ -59,13 +59,11 @@ type Settings = { /** * Test that the given app can be built by TypeScript without any type errors. * - * - Nexus generateSchema will be run before TypeScript to ensure typegen is present. - * - By default looks for an `__app.ts` entrypoint - * - All entrypoint exports are expected to be Nexus type definitions - * - Except the optional export name "plugins" which is treated as an array of plugins for makeSchema - * - Outputs a `__typegen.ts` typegen module - * - You must import the typegen module into your entrypoint module - * - If you provide a `tsconfig.json` file in the root dir it will be used. + * - Nexus generateSchema will be run before TypeScript to ensure typegen is present. - By default looks for + * an `__app.ts` entrypoint - All entrypoint exports are expected to be Nexus type definitions - Except the + * optional export name "plugins" which is treated as an array of plugins for makeSchema - Outputs a + * `__typegen.ts` typegen module - You must import the typegen module into your entrypoint module - If you + * provide a `tsconfig.json` file in the root dir it will be used. */ export function testApp(settings: Settings & HookSettings) { const name = settings?.name ?? 'app' diff --git a/tests/integrations/abstractTypes/allStrategiesOptionalWhenTypeNameEnabled/case.spec.ts b/tests/integrations/abstractTypes/allStrategiesOptionalWhenTypeNameEnabled/case.spec.ts index a41dea12..dcf06040 100644 --- a/tests/integrations/abstractTypes/allStrategiesOptionalWhenTypeNameEnabled/case.spec.ts +++ b/tests/integrations/abstractTypes/allStrategiesOptionalWhenTypeNameEnabled/case.spec.ts @@ -1,8 +1,6 @@ import { testApp } from '../../../__helpers/testApp' -/** - * Ensures that resolveType and isTypeOf strategies are set to optional when __typename strategy is enabled - */ +/** Ensures that resolveType and isTypeOf strategies are set to optional when __typename strategy is enabled */ testApp({ rootDir: __dirname, name: 'allStrategiesOptionalWhenTypeNameEnabled', diff --git a/tests/integrations/abstractTypes/isTypeOfsImplemented/case.spec.ts b/tests/integrations/abstractTypes/isTypeOfsImplemented/case.spec.ts index fb0b5dff..e0dbf367 100644 --- a/tests/integrations/abstractTypes/isTypeOfsImplemented/case.spec.ts +++ b/tests/integrations/abstractTypes/isTypeOfsImplemented/case.spec.ts @@ -1,7 +1,8 @@ import { testApp } from '../../../__helpers/testApp' /** - * Ensures that when resolveType and isTypeOf are true, if all isTypeOf are implemented, the resolveType implementation become optional + * Ensures that when resolveType and isTypeOf are true, if all isTypeOf are implemented, the resolveType + * implementation become optional */ testApp({ rootDir: __dirname, diff --git a/tests/integrations/abstractTypes/resolveTypeImplemented/case.spec.ts b/tests/integrations/abstractTypes/resolveTypeImplemented/case.spec.ts index 178ddb86..70ac40ed 100644 --- a/tests/integrations/abstractTypes/resolveTypeImplemented/case.spec.ts +++ b/tests/integrations/abstractTypes/resolveTypeImplemented/case.spec.ts @@ -1,7 +1,8 @@ import { testApp } from '../../../__helpers/testApp' /** - * Ensures that when resolveType and isTypeOf are true, if resolveType is implemented, isTypeOf implementations become optionals + * Ensures that when resolveType and isTypeOf are true, if resolveType is implemented, isTypeOf + * implementations become optionals */ testApp({ rootDir: __dirname, From 19b7b7717c3f4d55635ce889cc54df0ee1a564d7 Mon Sep 17 00:00:00 2001 From: Tim Griesser Date: Sun, 6 Dec 2020 15:42:17 -0500 Subject: [PATCH 2/2] Skip windows --- .github/workflows/pr.yml | 5 ++++- .github/workflows/trunk.yml | 7 +++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/.github/workflows/pr.yml b/.github/workflows/pr.yml index 16fbe657..74072b4d 100644 --- a/.github/workflows/pr.yml +++ b/.github/workflows/pr.yml @@ -29,7 +29,10 @@ jobs: with: node-version: ${{ matrix.node-version }} - name: Install Dependencies - run: yarn --frozen-lockfile && yarn format:ci + run: yarn --frozen-lockfile + - name: Check Prettier + if: matrix.os != 'windows-latest' + run: yarn format:ci - name: Test run: yarn -s test:ci - name: Upload coverage to Codecov diff --git a/.github/workflows/trunk.yml b/.github/workflows/trunk.yml index 9c645783..51d21806 100644 --- a/.github/workflows/trunk.yml +++ b/.github/workflows/trunk.yml @@ -13,7 +13,7 @@ jobs: with: node-version: 12.x - name: Install Dependencies - run: yarn --frozen-lockfile && yarn format:ci + run: yarn --frozen-lockfile - name: Install GraphQL@14.x run: yarn add graphql@^14.5.8 - name: Test @@ -31,7 +31,10 @@ jobs: with: node-version: ${{ matrix.node-version }} - name: Install Dependencies - run: yarn --frozen-lockfile && yarn format:ci + run: yarn --frozen-lockfile + - name: Check Prettier + if: matrix.os != 'windows-latest' + run: yarn format:ci - name: Test run: yarn -s test:ci - name: Upload coverage to Codecov