Skip to content

Commit d775b3c

Browse files
authored
Merge pull request #4 from Code-Hex/add/prettier
add prettier
2 parents 6290cdc + 039a426 commit d775b3c

File tree

15 files changed

+287
-375
lines changed

15 files changed

+287
-375
lines changed

.github/workflows/ci.yml

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ jobs:
2323
- run: yarn install --frozen-lockfile
2424
- run: yarn test
2525
env:
26-
CI: true
26+
CI: true
2727
eslint:
2828
runs-on: ubuntu-latest
2929
steps:
@@ -41,6 +41,7 @@ jobs:
4141
${{ runner.os }}-yarn-
4242
- run: yarn install --frozen-lockfile
4343
- run: yarn lint-fix
44+
- run: yarn prettier
4445
- name: Auto commit fixed code
4546
id: auto-commit-action
4647
uses: stefanzweifel/git-auto-commit-action@v4

.prettierrc.json

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
{
2+
"trailingComma": "es5",
3+
"printWidth": 120,
4+
"singleQuote": true,
5+
"arrowParens": "avoid"
6+
}

codegen.yml

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
overwrite: true
2-
schema: "./test.graphql"
2+
schema: './test.graphql'
33
generates:
44
gen/types.ts:
55
plugins:
@@ -17,11 +17,11 @@ generates:
1717
constraint:
1818
minLength: min # same as ['min', '$1']
1919
maxLength: max
20-
startsWith: ["matches", "/^$1/"]
21-
endsWith: ["matches", "/$1$/"]
22-
contains: ["matches", "/$1/"]
23-
notContains: ["matches", "/^((?!$1).)*$/"]
24-
pattern: ["matches", "/$1/"]
20+
startsWith: ['matches', '/^$1/']
21+
endsWith: ['matches', '/$1$/']
22+
contains: ['matches', '/$1/']
23+
notContains: ['matches', '/^((?!$1).)*$/']
24+
pattern: ['matches', '/$1/']
2525
format:
2626
# For example, `@constraint(format: "uri")`. this case $1 will be "uri".
2727
# Therefore the generator generates yup schema `.url()` followed by `uri: 'url'`
@@ -33,7 +33,7 @@ generates:
3333
# you need to add the logic using `yup.addMethod`.
3434
# see: https://github.com/jquense/yup#addmethodschematype-schema-name-string-method--schema-void
3535
ipv4: ipv4
36-
min: ["min", "$1 - 1"]
37-
max: ["max", "$1 + 1"]
36+
min: ['min', '$1 - 1']
37+
max: ['max', '$1 + 1']
3838
exclusiveMin: min
39-
exclusiveMax: max
39+
exclusiveMax: max

package.json

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,8 @@
2525
"build:module": "tsc -p tsconfig.module.json",
2626
"lint": "eslint --ext .ts .",
2727
"lint-fix": "eslint --fix --ext .ts .",
28+
"prettier": "prettier --ignore-path .gitignore --write --list-different \"**/*.{ts,graphql,yml}\"",
29+
"prettier:check": "prettier --ignore-path .gitignore --check \"**/*.{ts,graphql,yml}\"",
2830
"generate": "run-p build:* && graphql-codegen",
2931
"prepublish": "run-p build:*"
3032
},
@@ -54,6 +56,7 @@
5456
"eslint": "^8.7.0",
5557
"jest": "^27.4.7",
5658
"npm-run-all": "^4.1.5",
59+
"prettier": "2.5.1",
5760
"ts-jest": "^27.1.3",
5861
"typescript": "^4.5.4",
5962
"yup": "^0.32.11"

src/config.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
1-
import { TypeScriptPluginConfig } from "@graphql-codegen/typescript";
1+
import { TypeScriptPluginConfig } from '@graphql-codegen/typescript';
22

3-
export type ValidationSchema = "yup";
3+
export type ValidationSchema = 'yup';
44

55
export interface DirectiveConfig {
66
[directive: string]: {

src/directive.ts

Lines changed: 27 additions & 57 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,6 @@
1-
import {
2-
ConstArgumentNode,
3-
ConstDirectiveNode,
4-
ConstValueNode,
5-
Kind,
6-
valueFromASTUntyped,
7-
} from "graphql";
8-
import { DirectiveConfig, DirectiveObjectArguments } from "./config";
9-
import { isConvertableRegexp } from "./regexp";
1+
import { ConstArgumentNode, ConstDirectiveNode, ConstValueNode, Kind, valueFromASTUntyped } from 'graphql';
2+
import { DirectiveConfig, DirectiveObjectArguments } from './config';
3+
import { isConvertableRegexp } from './regexp';
104

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

2317
const isFormattedDirectiveObjectArguments = (
2418
arg: FormattedDirectiveArguments[keyof FormattedDirectiveArguments]
25-
): arg is FormattedDirectiveObjectArguments =>
26-
arg !== undefined && !Array.isArray(arg);
19+
): arg is FormattedDirectiveObjectArguments => arg !== undefined && !Array.isArray(arg);
2720

2821
// ```yml
2922
// directives:
@@ -49,18 +42,16 @@ const isFormattedDirectiveObjectArguments = (
4942
// }
5043
// }
5144
// }
52-
export const formatDirectiveConfig = (
53-
config: DirectiveConfig
54-
): FormattedDirectiveConfig => {
45+
export const formatDirectiveConfig = (config: DirectiveConfig): FormattedDirectiveConfig => {
5546
return Object.fromEntries(
5647
Object.entries(config).map(([directive, arg]) => {
5748
const formatted = Object.fromEntries(
5849
Object.entries(arg).map(([arg, val]) => {
5950
if (Array.isArray(val)) {
6051
return [arg, val];
6152
}
62-
if (typeof val === "string") {
63-
return [arg, [val, "$1"]];
53+
if (typeof val === 'string') {
54+
return [arg, [val, '$1']];
6455
}
6556
return [arg, formatDirectiveObjectArguments(val)];
6657
})
@@ -84,14 +75,12 @@ export const formatDirectiveConfig = (
8475
// 'uri': ['url', '$2'],
8576
// 'email': ['email'],
8677
// }
87-
export const formatDirectiveObjectArguments = (
88-
args: DirectiveObjectArguments
89-
): FormattedDirectiveObjectArguments => {
78+
export const formatDirectiveObjectArguments = (args: DirectiveObjectArguments): FormattedDirectiveObjectArguments => {
9079
const formatted = Object.entries(args).map(([arg, val]) => {
9180
if (Array.isArray(val)) {
9281
return [arg, val];
9382
}
94-
return [arg, [val, "$2"]];
83+
return [arg, [val, '$2']];
9584
});
9685
return Object.fromEntries(formatted);
9786
};
@@ -118,107 +107,88 @@ export const formatDirectiveObjectArguments = (
118107
// email: String! @required(msg: "message") @constraint(minLength: 100, format: "email")
119108
// }
120109
// ```
121-
export const buildApi = (
122-
config: FormattedDirectiveConfig,
123-
directives: ReadonlyArray<ConstDirectiveNode>
124-
): string =>
110+
export const buildApi = (config: FormattedDirectiveConfig, directives: ReadonlyArray<ConstDirectiveNode>): string =>
125111
directives
126-
.map((directive) => {
112+
.map(directive => {
127113
const directiveName = directive.name.value;
128114
const argsConfig = config[directiveName];
129-
return buildApiFromDirectiveArguments(
130-
argsConfig,
131-
directive.arguments ?? []
132-
);
115+
return buildApiFromDirectiveArguments(argsConfig, directive.arguments ?? []);
133116
})
134-
.join("");
117+
.join('');
135118

136-
const buildApiSchema = (
137-
validationSchema: string[] | undefined,
138-
argValue: ConstValueNode
139-
): string => {
119+
const buildApiSchema = (validationSchema: string[] | undefined, argValue: ConstValueNode): string => {
140120
if (!validationSchema) {
141-
return "";
121+
return '';
142122
}
143123
const schemaApi = validationSchema[0];
144-
const schemaApiArgs = validationSchema.slice(1).map((templateArg) => {
124+
const schemaApiArgs = validationSchema.slice(1).map(templateArg => {
145125
const gqlSchemaArgs = apiArgsFromConstValueNode(argValue);
146126
return applyArgToApiSchemaTemplate(templateArg, gqlSchemaArgs);
147127
});
148-
return `.${schemaApi}(${schemaApiArgs.join(", ")})`;
128+
return `.${schemaApi}(${schemaApiArgs.join(', ')})`;
149129
};
150130

151131
const buildApiFromDirectiveArguments = (
152132
config: FormattedDirectiveArguments,
153133
args: ReadonlyArray<ConstArgumentNode>
154134
): string => {
155135
return args
156-
.map((arg) => {
136+
.map(arg => {
157137
const argName = arg.name.value;
158138
const validationSchema = config[argName];
159139
if (isFormattedDirectiveObjectArguments(validationSchema)) {
160-
return buildApiFromDirectiveObjectArguments(
161-
validationSchema,
162-
arg.value
163-
);
140+
return buildApiFromDirectiveObjectArguments(validationSchema, arg.value);
164141
}
165142
return buildApiSchema(validationSchema, arg.value);
166143
})
167-
.join("");
144+
.join('');
168145
};
169146

170147
const buildApiFromDirectiveObjectArguments = (
171148
config: FormattedDirectiveObjectArguments,
172149
argValue: ConstValueNode
173150
): string => {
174151
if (argValue.kind !== Kind.STRING) {
175-
return "";
152+
return '';
176153
}
177154
const validationSchema = config[argValue.value];
178155
return buildApiSchema(validationSchema, argValue);
179156
};
180157

181-
const applyArgToApiSchemaTemplate = (
182-
template: string,
183-
apiArgs: any[]
184-
): string => {
158+
const applyArgToApiSchemaTemplate = (template: string, apiArgs: any[]): string => {
185159
const matches = template.matchAll(/[$](\d+)/g);
186160
for (const match of matches) {
187161
const placeholder = match[0]; // `$1`
188162
const idx = parseInt(match[1], 10) - 1; // start with `1 - 1`
189163
const apiArg = apiArgs[idx];
190164
if (!apiArg) {
191-
template = template.replace(placeholder, "");
165+
template = template.replace(placeholder, '');
192166
continue;
193167
}
194168
if (template === placeholder) {
195169
return stringify(apiArg);
196170
}
197171
template = template.replace(placeholder, apiArg);
198172
}
199-
if (template !== "") {
173+
if (template !== '') {
200174
return stringify(template, true);
201175
}
202176
return template;
203177
};
204178

205179
const stringify = (arg: any, quoteString?: boolean): string => {
206180
if (Array.isArray(arg)) {
207-
return arg.map((v) => stringify(v, true)).join(",");
181+
return arg.map(v => stringify(v, true)).join(',');
208182
}
209-
if (typeof arg === "string") {
183+
if (typeof arg === 'string') {
210184
if (isConvertableRegexp(arg)) {
211185
return arg;
212186
}
213187
if (quoteString) {
214188
return JSON.stringify(arg);
215189
}
216190
}
217-
if (
218-
typeof arg === "boolean" ||
219-
typeof arg === "number" ||
220-
typeof arg === "bigint"
221-
) {
191+
if (typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'bigint') {
222192
return `${arg}`;
223193
}
224194
return JSON.stringify(arg);

src/graphql.ts

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,7 @@
1-
import {
2-
ListTypeNode,
3-
NonNullTypeNode,
4-
NamedTypeNode,
5-
TypeNode,
6-
} from "graphql";
1+
import { ListTypeNode, NonNullTypeNode, NamedTypeNode, TypeNode } from 'graphql';
72

8-
export const isListType = (typ?: TypeNode): typ is ListTypeNode =>
9-
typ?.kind === "ListType";
10-
export const isNonNullType = (typ?: TypeNode): typ is NonNullTypeNode =>
11-
typ?.kind === "NonNullType";
12-
export const isNamedType = (typ?: TypeNode): typ is NamedTypeNode =>
13-
typ?.kind === "NamedType";
3+
export const isListType = (typ?: TypeNode): typ is ListTypeNode => typ?.kind === 'ListType';
4+
export const isNonNullType = (typ?: TypeNode): typ is NonNullTypeNode => typ?.kind === 'NonNullType';
5+
export const isNamedType = (typ?: TypeNode): typ is NamedTypeNode => typ?.kind === 'NamedType';
146

15-
export const isInput = (kind: string) => kind.includes("Input");
7+
export const isInput = (kind: string) => kind.includes('Input');

src/index.ts

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,10 @@
1-
import { transformSchemaAST } from "@graphql-codegen/schema-ast";
2-
import { YupSchemaVisitor } from "./yup/index";
3-
import { ValidationSchemaPluginConfig } from "./config";
4-
import {
5-
oldVisit,
6-
PluginFunction,
7-
Types,
8-
} from "@graphql-codegen/plugin-helpers";
9-
import { GraphQLSchema } from "graphql";
1+
import { transformSchemaAST } from '@graphql-codegen/schema-ast';
2+
import { YupSchemaVisitor } from './yup/index';
3+
import { ValidationSchemaPluginConfig } from './config';
4+
import { oldVisit, PluginFunction, Types } from '@graphql-codegen/plugin-helpers';
5+
import { GraphQLSchema } from 'graphql';
106

11-
export const plugin: PluginFunction<
12-
ValidationSchemaPluginConfig,
13-
Types.ComplexPluginOutput
14-
> = (
7+
export const plugin: PluginFunction<ValidationSchemaPluginConfig, Types.ComplexPluginOutput> = (
158
schema: GraphQLSchema,
169
_documents: Types.DocumentFile[],
1710
config: ValidationSchemaPluginConfig
@@ -25,10 +18,10 @@ export const plugin: PluginFunction<
2518

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

3023
return {
3124
prepend: buildImports(),
32-
content: "\n" + [...generated].join("\n"),
25+
content: '\n' + [...generated].join('\n'),
3326
};
3427
};

src/regexp.ts

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,2 @@
11
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#advanced_searching_with_flags
2-
export const isConvertableRegexp = (maybeRegexp: string): boolean =>
3-
/^\/.*\/[dgimsuy]*$/.test(maybeRegexp);
2+
export const isConvertableRegexp = (maybeRegexp: string): boolean => /^\/.*\/[dgimsuy]*$/.test(maybeRegexp);

0 commit comments

Comments
 (0)