Skip to content

add prettier #4

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jan 23, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ jobs:
- run: yarn install --frozen-lockfile
- run: yarn test
env:
CI: true
CI: true
eslint:
runs-on: ubuntu-latest
steps:
Expand All @@ -41,6 +41,7 @@ jobs:
${{ runner.os }}-yarn-
- run: yarn install --frozen-lockfile
- run: yarn lint-fix
- run: yarn prettier
- name: Auto commit fixed code
id: auto-commit-action
uses: stefanzweifel/git-auto-commit-action@v4
Expand Down
6 changes: 6 additions & 0 deletions .prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"trailingComma": "es5",
"printWidth": 120,
"singleQuote": true,
"arrowParens": "avoid"
}
18 changes: 9 additions & 9 deletions codegen.yml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
overwrite: true
schema: "./test.graphql"
schema: './test.graphql'
generates:
gen/types.ts:
plugins:
Expand All @@ -17,11 +17,11 @@ generates:
constraint:
minLength: min # same as ['min', '$1']
maxLength: max
startsWith: ["matches", "/^$1/"]
endsWith: ["matches", "/$1$/"]
contains: ["matches", "/$1/"]
notContains: ["matches", "/^((?!$1).)*$/"]
pattern: ["matches", "/$1/"]
startsWith: ['matches', '/^$1/']
endsWith: ['matches', '/$1$/']
contains: ['matches', '/$1/']
notContains: ['matches', '/^((?!$1).)*$/']
pattern: ['matches', '/$1/']
format:
# For example, `@constraint(format: "uri")`. this case $1 will be "uri".
# Therefore the generator generates yup schema `.url()` followed by `uri: 'url'`
Expand All @@ -33,7 +33,7 @@ generates:
# you need to add the logic using `yup.addMethod`.
# see: https://github.com/jquense/yup#addmethodschematype-schema-name-string-method--schema-void
ipv4: ipv4
min: ["min", "$1 - 1"]
max: ["max", "$1 + 1"]
min: ['min', '$1 - 1']
max: ['max', '$1 + 1']
exclusiveMin: min
exclusiveMax: max
exclusiveMax: max
3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@
"build:module": "tsc -p tsconfig.module.json",
"lint": "eslint --ext .ts .",
"lint-fix": "eslint --fix --ext .ts .",
"prettier": "prettier --ignore-path .gitignore --write --list-different \"**/*.{ts,graphql,yml}\"",
"prettier:check": "prettier --ignore-path .gitignore --check \"**/*.{ts,graphql,yml}\"",
"generate": "run-p build:* && graphql-codegen",
"prepublish": "run-p build:*"
},
Expand Down Expand Up @@ -54,6 +56,7 @@
"eslint": "^8.7.0",
"jest": "^27.4.7",
"npm-run-all": "^4.1.5",
"prettier": "2.5.1",
"ts-jest": "^27.1.3",
"typescript": "^4.5.4",
"yup": "^0.32.11"
Expand Down
4 changes: 2 additions & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { TypeScriptPluginConfig } from "@graphql-codegen/typescript";
import { TypeScriptPluginConfig } from '@graphql-codegen/typescript';

export type ValidationSchema = "yup";
export type ValidationSchema = 'yup';

export interface DirectiveConfig {
[directive: string]: {
Expand Down
84 changes: 27 additions & 57 deletions src/directive.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,6 @@
import {
ConstArgumentNode,
ConstDirectiveNode,
ConstValueNode,
Kind,
valueFromASTUntyped,
} from "graphql";
import { DirectiveConfig, DirectiveObjectArguments } from "./config";
import { isConvertableRegexp } from "./regexp";
import { ConstArgumentNode, ConstDirectiveNode, ConstValueNode, Kind, valueFromASTUntyped } from 'graphql';
import { DirectiveConfig, DirectiveObjectArguments } from './config';
import { isConvertableRegexp } from './regexp';

export interface FormattedDirectiveConfig {
[directive: string]: FormattedDirectiveArguments;
Expand All @@ -22,8 +16,7 @@ export interface FormattedDirectiveObjectArguments {

const isFormattedDirectiveObjectArguments = (
arg: FormattedDirectiveArguments[keyof FormattedDirectiveArguments]
): arg is FormattedDirectiveObjectArguments =>
arg !== undefined && !Array.isArray(arg);
): arg is FormattedDirectiveObjectArguments => arg !== undefined && !Array.isArray(arg);

// ```yml
// directives:
Expand All @@ -49,18 +42,16 @@ const isFormattedDirectiveObjectArguments = (
// }
// }
// }
export const formatDirectiveConfig = (
config: DirectiveConfig
): FormattedDirectiveConfig => {
export const formatDirectiveConfig = (config: DirectiveConfig): FormattedDirectiveConfig => {
return Object.fromEntries(
Object.entries(config).map(([directive, arg]) => {
const formatted = Object.fromEntries(
Object.entries(arg).map(([arg, val]) => {
if (Array.isArray(val)) {
return [arg, val];
}
if (typeof val === "string") {
return [arg, [val, "$1"]];
if (typeof val === 'string') {
return [arg, [val, '$1']];
}
return [arg, formatDirectiveObjectArguments(val)];
})
Expand All @@ -84,14 +75,12 @@ export const formatDirectiveConfig = (
// 'uri': ['url', '$2'],
// 'email': ['email'],
// }
export const formatDirectiveObjectArguments = (
args: DirectiveObjectArguments
): FormattedDirectiveObjectArguments => {
export const formatDirectiveObjectArguments = (args: DirectiveObjectArguments): FormattedDirectiveObjectArguments => {
const formatted = Object.entries(args).map(([arg, val]) => {
if (Array.isArray(val)) {
return [arg, val];
}
return [arg, [val, "$2"]];
return [arg, [val, '$2']];
});
return Object.fromEntries(formatted);
};
Expand All @@ -118,107 +107,88 @@ export const formatDirectiveObjectArguments = (
// email: String! @required(msg: "message") @constraint(minLength: 100, format: "email")
// }
// ```
export const buildApi = (
config: FormattedDirectiveConfig,
directives: ReadonlyArray<ConstDirectiveNode>
): string =>
export const buildApi = (config: FormattedDirectiveConfig, directives: ReadonlyArray<ConstDirectiveNode>): string =>
directives
.map((directive) => {
.map(directive => {
const directiveName = directive.name.value;
const argsConfig = config[directiveName];
return buildApiFromDirectiveArguments(
argsConfig,
directive.arguments ?? []
);
return buildApiFromDirectiveArguments(argsConfig, directive.arguments ?? []);
})
.join("");
.join('');

const buildApiSchema = (
validationSchema: string[] | undefined,
argValue: ConstValueNode
): string => {
const buildApiSchema = (validationSchema: string[] | undefined, argValue: ConstValueNode): string => {
if (!validationSchema) {
return "";
return '';
}
const schemaApi = validationSchema[0];
const schemaApiArgs = validationSchema.slice(1).map((templateArg) => {
const schemaApiArgs = validationSchema.slice(1).map(templateArg => {
const gqlSchemaArgs = apiArgsFromConstValueNode(argValue);
return applyArgToApiSchemaTemplate(templateArg, gqlSchemaArgs);
});
return `.${schemaApi}(${schemaApiArgs.join(", ")})`;
return `.${schemaApi}(${schemaApiArgs.join(', ')})`;
};

const buildApiFromDirectiveArguments = (
config: FormattedDirectiveArguments,
args: ReadonlyArray<ConstArgumentNode>
): string => {
return args
.map((arg) => {
.map(arg => {
const argName = arg.name.value;
const validationSchema = config[argName];
if (isFormattedDirectiveObjectArguments(validationSchema)) {
return buildApiFromDirectiveObjectArguments(
validationSchema,
arg.value
);
return buildApiFromDirectiveObjectArguments(validationSchema, arg.value);
}
return buildApiSchema(validationSchema, arg.value);
})
.join("");
.join('');
};

const buildApiFromDirectiveObjectArguments = (
config: FormattedDirectiveObjectArguments,
argValue: ConstValueNode
): string => {
if (argValue.kind !== Kind.STRING) {
return "";
return '';
}
const validationSchema = config[argValue.value];
return buildApiSchema(validationSchema, argValue);
};

const applyArgToApiSchemaTemplate = (
template: string,
apiArgs: any[]
): string => {
const applyArgToApiSchemaTemplate = (template: string, apiArgs: any[]): string => {
const matches = template.matchAll(/[$](\d+)/g);
for (const match of matches) {
const placeholder = match[0]; // `$1`
const idx = parseInt(match[1], 10) - 1; // start with `1 - 1`
const apiArg = apiArgs[idx];
if (!apiArg) {
template = template.replace(placeholder, "");
template = template.replace(placeholder, '');
continue;
}
if (template === placeholder) {
return stringify(apiArg);
}
template = template.replace(placeholder, apiArg);
}
if (template !== "") {
if (template !== '') {
return stringify(template, true);
}
return template;
};

const stringify = (arg: any, quoteString?: boolean): string => {
if (Array.isArray(arg)) {
return arg.map((v) => stringify(v, true)).join(",");
return arg.map(v => stringify(v, true)).join(',');
}
if (typeof arg === "string") {
if (typeof arg === 'string') {
if (isConvertableRegexp(arg)) {
return arg;
}
if (quoteString) {
return JSON.stringify(arg);
}
}
if (
typeof arg === "boolean" ||
typeof arg === "number" ||
typeof arg === "bigint"
) {
if (typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'bigint') {
return `${arg}`;
}
return JSON.stringify(arg);
Expand Down
18 changes: 5 additions & 13 deletions src/graphql.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,7 @@
import {
ListTypeNode,
NonNullTypeNode,
NamedTypeNode,
TypeNode,
} from "graphql";
import { ListTypeNode, NonNullTypeNode, NamedTypeNode, TypeNode } from 'graphql';

export const isListType = (typ?: TypeNode): typ is ListTypeNode =>
typ?.kind === "ListType";
export const isNonNullType = (typ?: TypeNode): typ is NonNullTypeNode =>
typ?.kind === "NonNullType";
export const isNamedType = (typ?: TypeNode): typ is NamedTypeNode =>
typ?.kind === "NamedType";
export const isListType = (typ?: TypeNode): typ is ListTypeNode => typ?.kind === 'ListType';
export const isNonNullType = (typ?: TypeNode): typ is NonNullTypeNode => typ?.kind === 'NonNullType';
export const isNamedType = (typ?: TypeNode): typ is NamedTypeNode => typ?.kind === 'NamedType';

export const isInput = (kind: string) => kind.includes("Input");
export const isInput = (kind: string) => kind.includes('Input');
23 changes: 8 additions & 15 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,10 @@
import { transformSchemaAST } from "@graphql-codegen/schema-ast";
import { YupSchemaVisitor } from "./yup/index";
import { ValidationSchemaPluginConfig } from "./config";
import {
oldVisit,
PluginFunction,
Types,
} from "@graphql-codegen/plugin-helpers";
import { GraphQLSchema } from "graphql";
import { transformSchemaAST } from '@graphql-codegen/schema-ast';
import { YupSchemaVisitor } from './yup/index';
import { ValidationSchemaPluginConfig } from './config';
import { oldVisit, PluginFunction, Types } from '@graphql-codegen/plugin-helpers';
import { GraphQLSchema } from 'graphql';

export const plugin: PluginFunction<
ValidationSchemaPluginConfig,
Types.ComplexPluginOutput
> = (
export const plugin: PluginFunction<ValidationSchemaPluginConfig, Types.ComplexPluginOutput> = (
schema: GraphQLSchema,
_documents: Types.DocumentFile[],
config: ValidationSchemaPluginConfig
Expand All @@ -25,10 +18,10 @@ export const plugin: PluginFunction<

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
const generated = result.definitions.filter((def) => typeof def === "string");
const generated = result.definitions.filter(def => typeof def === 'string');

return {
prepend: buildImports(),
content: "\n" + [...generated].join("\n"),
content: '\n' + [...generated].join('\n'),
};
};
3 changes: 1 addition & 2 deletions src/regexp.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#advanced_searching_with_flags
export const isConvertableRegexp = (maybeRegexp: string): boolean =>
/^\/.*\/[dgimsuy]*$/.test(maybeRegexp);
export const isConvertableRegexp = (maybeRegexp: string): boolean => /^\/.*\/[dgimsuy]*$/.test(maybeRegexp);
Loading