@newmo/graphql-codegen-fake-server-client 0.9.5 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -80,6 +80,10 @@ it("register fake response for query", async () => {
80
80
 
81
81
  - `typesFile` (required): Path to the generated client's graphql file.
82
82
  - `fakeServerEndpoint` (optional): Fake server endpoint. Default is `http://127.0.0.1:4000/fake`.
83
+ - `namingConvention` (optional): Naming convention for the generated types. Default is `change-case#pascalCase`.
84
+ - [Naming Convention](https://the-guild.dev/graphql/codegen/docs/config-reference/naming-convention)
85
+ - `typesPrefix` (optional): Prefix for the generated types.
86
+ - `typesSuffix` (optional): Suffix for the generated types.
83
87
 
84
88
  ## License
85
89
 
@@ -7,9 +7,50 @@ const plugin = {
7
7
  const config = (0, config_1.normalizeConfig)(rawConfig);
8
8
  const fakeEndpoint = config.fakeServerEndpoint;
9
9
  const registerOperationResponseType = "{ ok: true } | { ok: false; errors: string[] }";
10
- const generateRegisterOperation = (name) => {
11
- return `export async function register${name}QueryResponse(sequenceId:string, queryResponse: ${name}Query): Promise<${registerOperationResponseType}> {
12
- return await fetch('${fakeEndpoint}', {
10
+ const indentEachLine = (indent, text) => {
11
+ return text
12
+ .split("\n")
13
+ .map((line) => `${indent}${line}`)
14
+ .join("\n");
15
+ };
16
+ const generateFakeClient = (exportsFunctions) => {
17
+ const indent = " ";
18
+ return `\
19
+ export type CreateFakeClientOptions = {
20
+ /**
21
+ * The URL of the fake server
22
+ * @example 'http://localhost:4000/fake'
23
+ */
24
+ fakeServerEndpoint: string;
25
+ };
26
+ export function createFakeClient(options: CreateFakeClientOptions) {
27
+ if(!options.fakeServerEndpoint.endsWith('/fake')) {
28
+ throw new Error('fakeServerEndpoint must end with "/fake"');
29
+ }
30
+ return {
31
+ ${exportsFunctions
32
+ .flatMap((fn) => {
33
+ if (fn.type === "query") {
34
+ return [
35
+ indentEachLine(`${indent}${indent}`, generateRegisterOperationMethod(fn.name, "options.fakeServerEndpoint")),
36
+ indentEachLine(`${indent}${indent}`, generateRegisterOperationErrorMethod(fn.name, "options.fakeServerEndpoint")),
37
+ ];
38
+ }
39
+ if (fn.type === "mutation") {
40
+ return [
41
+ indentEachLine(`${indent}${indent}`, generateRegisterMutationMethod(fn.name, "options.fakeServerEndpoint")),
42
+ indentEachLine(`${indent}${indent}`, generateRegisterMutationErrorMethod(fn.name, "options.fakeServerEndpoint")),
43
+ ];
44
+ }
45
+ throw new Error(`Unknown type${fn}`);
46
+ })
47
+ .join(",\n")}
48
+ };
49
+ }`;
50
+ };
51
+ const generateRegisterOperationMethod = (name, fakeEndpointVariableName) => {
52
+ return `async register${name}QueryResponse(sequenceId:string, queryResponse: ${name}Query): Promise<${registerOperationResponseType}> {
53
+ return await fetch(${fakeEndpointVariableName}, {
13
54
  method: 'POST',
14
55
  headers: {
15
56
  'Content-Type': 'application/json',
@@ -23,9 +64,9 @@ const plugin = {
23
64
  }).then((res) => res.json()) as ${registerOperationResponseType};
24
65
  }`;
25
66
  };
26
- const generateRegisterOperationError = (name) => {
27
- return `export async function register${name}QueryErrorResponse(sequenceId:string, { errors, responseStatusCode }: { errors: Record<string, unknown>[]; responseStatusCode: number }): Promise<${registerOperationResponseType}> {
28
- return await fetch('${fakeEndpoint}', {
67
+ const generateRegisterOperationErrorMethod = (name, fakeEndpointVariableName) => {
68
+ return `async register${name}QueryErrorResponse(sequenceId:string, { errors, responseStatusCode }: { errors: Record<string, unknown>[]; responseStatusCode: number }): Promise<${registerOperationResponseType}> {
69
+ return await fetch(${fakeEndpointVariableName}, {
29
70
  method: 'POST',
30
71
  headers: {
31
72
  'Content-Type': 'application/json',
@@ -40,9 +81,9 @@ const plugin = {
40
81
  }).then((res) => res.json()) as ${registerOperationResponseType};
41
82
  }`;
42
83
  };
43
- const generateRegisterMutation = (name) => {
44
- return `export async function register${name}MutationResponse(sequenceId:string, mutationResponse: ${name}Mutation): Promise<${registerOperationResponseType}> {
45
- return await fetch('${fakeEndpoint}', {
84
+ const generateRegisterMutationMethod = (name, fakeEndpointVariableName) => {
85
+ return `async register${name}MutationResponse(sequenceId:string, mutationResponse: ${name}Mutation): Promise<${registerOperationResponseType}> {
86
+ return await fetch(${fakeEndpointVariableName}, {
46
87
  method: 'POST',
47
88
  headers: {
48
89
  'Content-Type': 'application/json',
@@ -56,9 +97,9 @@ const plugin = {
56
97
  }).then((res) => res.json()) as ${registerOperationResponseType};
57
98
  }`;
58
99
  };
59
- const generateRegisterMutationError = (name) => {
60
- return `export async function register${name}MutationErrorResponse(sequenceId:string, { errors, responseStatusCode }: { errors: Record<string, unknown>[]; responseStatusCode: number }): Promise<${registerOperationResponseType}> {
61
- return await fetch('${fakeEndpoint}', {
100
+ const generateRegisterMutationErrorMethod = (name, fakeEndpointVariableName) => {
101
+ return `async register${name}MutationErrorResponse(sequenceId:string, { errors, responseStatusCode }: { errors: Record<string, unknown>[]; responseStatusCode: number }): Promise<${registerOperationResponseType}> {
102
+ return await fetch(${fakeEndpointVariableName}, {
62
103
  method: 'POST',
63
104
  headers: {
64
105
  'Content-Type': 'application/json',
@@ -99,30 +140,32 @@ ${documents
99
140
  });
100
141
  })
101
142
  .join("\n")}
102
- ${documents
103
- .flatMap((document) => {
104
- return document.document?.definitions?.flatMap((definition) => {
105
- // query
143
+ ${generateFakeClient(documents.flatMap((document) => {
144
+ const flatMap = document.document?.definitions?.flatMap((definition) => {
106
145
  if (definition.kind === "OperationDefinition" &&
107
146
  definition.operation === "query" &&
108
147
  definition.name) {
109
148
  return [
110
- generateRegisterOperation((0, convertName_1.convertName)(definition.name.value, config)),
111
- generateRegisterOperationError((0, convertName_1.convertName)(definition.name.value, config)),
149
+ {
150
+ name: (0, convertName_1.convertName)(definition.name.value, config),
151
+ type: "query",
152
+ },
112
153
  ];
113
154
  }
114
155
  if (definition.kind === "OperationDefinition" &&
115
156
  definition.operation === "mutation" &&
116
157
  definition.name) {
117
158
  return [
118
- generateRegisterMutation((0, convertName_1.convertName)(definition.name.value, config)),
119
- generateRegisterMutationError((0, convertName_1.convertName)(definition.name.value, config)),
159
+ {
160
+ name: (0, convertName_1.convertName)(definition.name.value, config),
161
+ type: "mutation",
162
+ },
120
163
  ];
121
164
  }
122
165
  return [];
123
- });
124
- })
125
- .join("\n")}
166
+ }) ?? [];
167
+ return flatMap;
168
+ }))}
126
169
  `;
127
170
  },
128
171
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@newmo/graphql-codegen-fake-server-client",
3
- "version": "0.9.5",
3
+ "version": "0.10.0",
4
4
  "private": false,
5
5
  "description": "GraphQL Codegen plugin for generating a fake server client",
6
6
  "keywords": [
@@ -32,7 +32,8 @@
32
32
  "prepare": "npm run build",
33
33
  "build": "tsc",
34
34
  "lint": "tsc --noEmit",
35
- "test": "npm run build && npm run codegen",
35
+ "test": "npm run build && npm run codegen && npm run typecheck",
36
+ "typecheck": "tsc --noEmit -p tsconfig.test.json",
36
37
  "codegen": "graphql-codegen --config graphql-codegen.ts"
37
38
  },
38
39
  "dependencies": {
@@ -42,6 +43,7 @@
42
43
  "devDependencies": {
43
44
  "@graphql-codegen/cli": "^5.0.0",
44
45
  "@graphql-codegen/typescript": "^4.0.1",
46
+ "@graphql-typed-document-node/core": "^3.2.0",
45
47
  "@tsconfig/node18": "^18.2.0",
46
48
  "@tsconfig/strictest": "^2.0.1",
47
49
  "@types/eslint": "^8.44.2",
@@ -59,5 +61,5 @@
59
61
  "access": "public",
60
62
  "registry": "https://registry.npmjs.org/"
61
63
  },
62
- "gitHead": "a57138a4d383886c967ccb31c5d50d8075331f7c"
64
+ "gitHead": "96211dee245e0aa305b35cb1d4312cb7484ef4e8"
63
65
  }
@@ -7,9 +7,74 @@ const plugin: CodegenPlugin<RawPluginConfig> = {
7
7
  const config = normalizeConfig(rawConfig);
8
8
  const fakeEndpoint = config.fakeServerEndpoint;
9
9
  const registerOperationResponseType = "{ ok: true } | { ok: false; errors: string[] }";
10
- const generateRegisterOperation = (name: string) => {
11
- return `export async function register${name}QueryResponse(sequenceId:string, queryResponse: ${name}Query): Promise<${registerOperationResponseType}> {
12
- return await fetch('${fakeEndpoint}', {
10
+ type GenerateFakeFunction =
11
+ | {
12
+ type: "query";
13
+ name: string;
14
+ }
15
+ | {
16
+ type: "mutation";
17
+ name: string;
18
+ };
19
+ const indentEachLine = (indent: string, text: string) => {
20
+ return text
21
+ .split("\n")
22
+ .map((line) => `${indent}${line}`)
23
+ .join("\n");
24
+ };
25
+ const generateFakeClient = (exportsFunctions: GenerateFakeFunction[]) => {
26
+ const indent = " ";
27
+ return `\
28
+ export type CreateFakeClientOptions = {
29
+ /**
30
+ * The URL of the fake server
31
+ * @example 'http://localhost:4000/fake'
32
+ */
33
+ fakeServerEndpoint: string;
34
+ };
35
+ export function createFakeClient(options: CreateFakeClientOptions) {
36
+ if(!options.fakeServerEndpoint.endsWith('/fake')) {
37
+ throw new Error('fakeServerEndpoint must end with "/fake"');
38
+ }
39
+ return {
40
+ ${exportsFunctions
41
+ .flatMap((fn) => {
42
+ if (fn.type === "query") {
43
+ return [
44
+ indentEachLine(
45
+ `${indent}${indent}`,
46
+ generateRegisterOperationMethod(fn.name, "options.fakeServerEndpoint"),
47
+ ),
48
+ indentEachLine(
49
+ `${indent}${indent}`,
50
+ generateRegisterOperationErrorMethod(fn.name, "options.fakeServerEndpoint"),
51
+ ),
52
+ ];
53
+ }
54
+ if (fn.type === "mutation") {
55
+ return [
56
+ indentEachLine(
57
+ `${indent}${indent}`,
58
+ generateRegisterMutationMethod(fn.name, "options.fakeServerEndpoint"),
59
+ ),
60
+ indentEachLine(
61
+ `${indent}${indent}`,
62
+ generateRegisterMutationErrorMethod(fn.name, "options.fakeServerEndpoint"),
63
+ ),
64
+ ];
65
+ }
66
+ throw new Error(`Unknown type${fn}`);
67
+ })
68
+ .join(",\n")}
69
+ };
70
+ }`;
71
+ };
72
+ const generateRegisterOperationMethod = (
73
+ name: string,
74
+ fakeEndpointVariableName: string,
75
+ ) => {
76
+ return `async register${name}QueryResponse(sequenceId:string, queryResponse: ${name}Query): Promise<${registerOperationResponseType}> {
77
+ return await fetch(${fakeEndpointVariableName}, {
13
78
  method: 'POST',
14
79
  headers: {
15
80
  'Content-Type': 'application/json',
@@ -23,9 +88,12 @@ const plugin: CodegenPlugin<RawPluginConfig> = {
23
88
  }).then((res) => res.json()) as ${registerOperationResponseType};
24
89
  }`;
25
90
  };
26
- const generateRegisterOperationError = (name: string) => {
27
- return `export async function register${name}QueryErrorResponse(sequenceId:string, { errors, responseStatusCode }: { errors: Record<string, unknown>[]; responseStatusCode: number }): Promise<${registerOperationResponseType}> {
28
- return await fetch('${fakeEndpoint}', {
91
+ const generateRegisterOperationErrorMethod = (
92
+ name: string,
93
+ fakeEndpointVariableName: string,
94
+ ) => {
95
+ return `async register${name}QueryErrorResponse(sequenceId:string, { errors, responseStatusCode }: { errors: Record<string, unknown>[]; responseStatusCode: number }): Promise<${registerOperationResponseType}> {
96
+ return await fetch(${fakeEndpointVariableName}, {
29
97
  method: 'POST',
30
98
  headers: {
31
99
  'Content-Type': 'application/json',
@@ -40,9 +108,9 @@ const plugin: CodegenPlugin<RawPluginConfig> = {
40
108
  }).then((res) => res.json()) as ${registerOperationResponseType};
41
109
  }`;
42
110
  };
43
- const generateRegisterMutation = (name: string) => {
44
- return `export async function register${name}MutationResponse(sequenceId:string, mutationResponse: ${name}Mutation): Promise<${registerOperationResponseType}> {
45
- return await fetch('${fakeEndpoint}', {
111
+ const generateRegisterMutationMethod = (name: string, fakeEndpointVariableName: string) => {
112
+ return `async register${name}MutationResponse(sequenceId:string, mutationResponse: ${name}Mutation): Promise<${registerOperationResponseType}> {
113
+ return await fetch(${fakeEndpointVariableName}, {
46
114
  method: 'POST',
47
115
  headers: {
48
116
  'Content-Type': 'application/json',
@@ -56,9 +124,12 @@ const plugin: CodegenPlugin<RawPluginConfig> = {
56
124
  }).then((res) => res.json()) as ${registerOperationResponseType};
57
125
  }`;
58
126
  };
59
- const generateRegisterMutationError = (name: string) => {
60
- return `export async function register${name}MutationErrorResponse(sequenceId:string, { errors, responseStatusCode }: { errors: Record<string, unknown>[]; responseStatusCode: number }): Promise<${registerOperationResponseType}> {
61
- return await fetch('${fakeEndpoint}', {
127
+ const generateRegisterMutationErrorMethod = (
128
+ name: string,
129
+ fakeEndpointVariableName: string,
130
+ ) => {
131
+ return `async register${name}MutationErrorResponse(sequenceId:string, { errors, responseStatusCode }: { errors: Record<string, unknown>[]; responseStatusCode: number }): Promise<${registerOperationResponseType}> {
132
+ return await fetch(${fakeEndpointVariableName}, {
62
133
  method: 'POST',
63
134
  headers: {
64
135
  'Content-Type': 'application/json',
@@ -107,34 +178,39 @@ ${documents
107
178
  });
108
179
  })
109
180
  .join("\n")}
110
- ${documents
111
- .flatMap((document) => {
112
- return document.document?.definitions?.flatMap((definition) => {
113
- // query
114
- if (
115
- definition.kind === "OperationDefinition" &&
116
- definition.operation === "query" &&
117
- definition.name
118
- ) {
119
- return [
120
- generateRegisterOperation(convertName(definition.name.value, config)),
121
- generateRegisterOperationError(convertName(definition.name.value, config)),
122
- ];
123
- }
124
- if (
125
- definition.kind === "OperationDefinition" &&
126
- definition.operation === "mutation" &&
127
- definition.name
128
- ) {
129
- return [
130
- generateRegisterMutation(convertName(definition.name.value, config)),
131
- generateRegisterMutationError(convertName(definition.name.value, config)),
132
- ];
133
- }
134
- return [];
135
- });
136
- })
137
- .join("\n")}
181
+ ${generateFakeClient(
182
+ documents.flatMap((document) => {
183
+ const flatMap =
184
+ document.document?.definitions?.flatMap((definition) => {
185
+ if (
186
+ definition.kind === "OperationDefinition" &&
187
+ definition.operation === "query" &&
188
+ definition.name
189
+ ) {
190
+ return [
191
+ {
192
+ name: convertName(definition.name.value, config),
193
+ type: "query",
194
+ },
195
+ ] satisfies GenerateFakeFunction[] as GenerateFakeFunction[];
196
+ }
197
+ if (
198
+ definition.kind === "OperationDefinition" &&
199
+ definition.operation === "mutation" &&
200
+ definition.name
201
+ ) {
202
+ return [
203
+ {
204
+ name: convertName(definition.name.value, config),
205
+ type: "mutation",
206
+ },
207
+ ] satisfies GenerateFakeFunction[] as GenerateFakeFunction[];
208
+ }
209
+ return [];
210
+ }) ?? [];
211
+ return flatMap satisfies GenerateFakeFunction[] as GenerateFakeFunction[];
212
+ }),
213
+ )}
138
214
  `;
139
215
  },
140
216
  };