-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
utils.ts
273 lines (249 loc) · 8.42 KB
/
utils.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import { initConfig, createSystem } from '@keystone-6/core/system';
import { getCommittedArtifacts } from '@keystone-6/core/artifacts';
import { KeystoneConfig, KeystoneContext, DatabaseProvider } from '@keystone-6/core/types';
export const dbProvider = process.env.TEST_ADAPTER as DatabaseProvider;
// This function injects the db configuration that we use for testing in CI.
// This functionality is a keystone repo specific way of doing things, so we don't
// export it from `@keystone-6/core/testing`.
export const apiTestConfig = (
config: Omit<KeystoneConfig, 'db'> & {
db?: Omit<KeystoneConfig['db'], 'provider' | 'url'>;
}
): KeystoneConfig => ({
...config,
db: {
...config.db,
provider: dbProvider,
url: process.env.DATABASE_URL as string,
},
});
export const unpackErrors = (errors: readonly any[] | undefined) =>
(errors || []).map(({ locations, ...unpacked }) => unpacked);
const j = (messages: string[]) => messages.map(m => ` - ${m}`).join('\n');
// FIXME: It's not clear to me right now why sometimes
// we get an expcetion, and other times we don't - TL
export const expectInternalServerError = (
errors: readonly any[] | undefined,
expectException: boolean,
args: { path: any[]; message: string }[]
) => {
const unpackedErrors = unpackErrors(errors);
expect(unpackedErrors).toEqual(
args.map(({ path, message }) => ({
extensions: {
code: 'INTERNAL_SERVER_ERROR',
...(expectException ? { exception: { locations: [expect.any(Object)], message } } : {}),
},
path,
message,
}))
);
};
export const expectGraphQLValidationError = (
errors: readonly any[] | undefined,
args: { message: string }[]
) => {
const unpackedErrors = unpackErrors(errors);
expect(unpackedErrors).toEqual(
args.map(({ message }) => ({ extensions: { code: 'GRAPHQL_VALIDATION_FAILED' }, message }))
);
};
export const expectAccessDenied = (
errors: readonly any[] | undefined,
args: { path: (string | number)[]; msg: string }[]
) => {
const unpackedErrors = (errors || []).map(({ locations, ...unpacked }) => ({
...unpacked,
}));
expect(unpackedErrors).toEqual(
args.map(({ path, msg }) => ({
extensions: { code: 'KS_ACCESS_DENIED' },
path,
message: `Access denied: ${msg}`,
}))
);
};
export const expectValidationError = (
errors: readonly any[] | undefined,
args: { path: (string | number)[]; messages: string[] }[]
) => {
const unpackedErrors = (errors || []).map(({ locations, ...unpacked }) => ({
...unpacked,
}));
expect(unpackedErrors).toEqual(
args.map(({ path, messages }) => ({
extensions: { code: 'KS_VALIDATION_FAILURE' },
path,
message: `You provided invalid data for this operation.\n${j(messages)}`,
}))
);
};
export const expectExtensionError = (
mode: 'dev' | 'production',
httpQuery: boolean,
_debug: boolean | undefined,
errors: readonly any[] | undefined,
extensionName: string,
args: { path: (string | number)[]; messages: string[]; debug: any[] }[]
) => {
const unpackedErrors = unpackErrors(errors);
expect(unpackedErrors).toEqual(
args.map(({ path, messages, debug }) => {
const message = `An error occured while running "${extensionName}".\n${j(messages)}`;
const stacktrace = message.split('\n');
stacktrace[0] = `Error: ${stacktrace[0]}`;
// We expect to see debug details if:
// - httpQuery is false
// - graphql.debug is true or
// - graphql.debug is undefined and mode !== production or
const expectDebug =
_debug === true || (_debug === undefined && mode !== 'production') || !httpQuery;
// We expect to see the Apollo exception under the same conditions, but only if
// httpQuery is also true.
const expectException = httpQuery && expectDebug;
return {
extensions: {
code: 'KS_EXTENSION_ERROR',
...(expectException
? { exception: { stacktrace: expect.arrayContaining(stacktrace) } }
: {}),
...(expectDebug ? { debug } : {}),
},
path,
message,
};
})
);
};
export const expectPrismaError = (
errors: readonly any[] | undefined,
args: { path: any[]; message: string; code: string; target: string[] }[]
) => {
const unpackedErrors = unpackErrors(errors);
expect(unpackedErrors).toEqual(
args.map(({ path, message, code, target }) => ({
extensions: {
code: 'KS_PRISMA_ERROR',
prisma: { clientVersion: '3.6.0', code, meta: { target } },
},
path,
message,
}))
);
};
export const expectLimitsExceededError = (
errors: readonly any[] | undefined,
args: { path: (string | number)[] }[]
) => {
const unpackedErrors = (errors || []).map(({ locations, ...unpacked }) => ({
...unpacked,
}));
const message = 'Your request exceeded server limits';
expect(unpackedErrors).toEqual(
args.map(({ path }) => ({ extensions: { code: 'KS_LIMITS_EXCEEDED' }, path, message }))
);
};
export const expectBadUserInput = (
errors: readonly any[] | undefined,
args: { path: any[]; message: string }[]
) => {
const unpackedErrors = unpackErrors(errors);
expect(unpackedErrors).toEqual(
args.map(({ path, message }) => ({
extensions: { code: 'KS_USER_INPUT_ERROR' },
path,
message: `Input error: ${message}`,
}))
);
};
export const expectAccessReturnError = (
errors: readonly any[] | undefined,
args: { path: any[]; errors: { tag: string; returned: string }[] }[]
) => {
const unpackedErrors = unpackErrors(errors);
expect(unpackedErrors).toEqual(
args.map(({ path, errors }) => {
const message = `Invalid values returned from access control function.\n${j(
errors.map(e => `${e.tag}: Returned: ${e.returned}. Expected: boolean.`)
)}`;
return { extensions: { code: 'KS_ACCESS_RETURN_ERROR' }, path, message };
})
);
};
export const expectFilterDenied = (
errors: readonly any[] | undefined,
args: { path: any[]; message: string }[]
) => {
const unpackedErrors = unpackErrors(errors);
expect(unpackedErrors).toEqual(
args.map(({ path, message }) => ({ extensions: { code: 'KS_FILTER_DENIED' }, path, message }))
);
};
export const expectResolverError = (
errors: readonly any[] | undefined,
args: { path: (string | number)[]; messages: string[]; debug: any[] }[]
) => {
const unpackedErrors = unpackErrors(errors);
expect(unpackedErrors).toEqual(
args.map(({ path, messages, debug }) => {
const message = `An error occured while resolving input fields.\n${j(messages)}`;
return { extensions: { code: 'KS_RESOLVER_ERROR', debug }, path, message };
})
);
};
export const expectSingleResolverError = (
errors: readonly any[] | undefined,
path: string,
fieldPath: string,
message: string
) =>
expectResolverError(errors, [
{
path: [path],
messages: [`${fieldPath}: ${message}`],
debug: [{ message, stacktrace: expect.stringMatching(new RegExp(`Error: ${message}\n`)) }],
},
]);
export const expectRelationshipError = (
errors: readonly any[] | undefined,
args: { path: (string | number)[]; messages: string[]; debug: any[] }[]
) => {
const unpackedErrors = unpackErrors(errors);
expect(unpackedErrors).toEqual(
args.map(({ path, messages, debug }) => {
const message = `An error occured while resolving relationship fields.\n${j(messages)}`;
return { extensions: { code: 'KS_RELATIONSHIP_ERROR', debug }, path, message };
})
);
};
export const expectSingleRelationshipError = (
errors: readonly any[] | undefined,
path: string,
fieldPath: string,
message: string
) =>
expectRelationshipError(errors, [
{
path: [path],
messages: [`${fieldPath}: ${message}`],
debug: [{ message, stacktrace: expect.stringMatching(new RegExp(`Error: ${message}\n`)) }],
},
]);
export async function seed<T extends Record<keyof T, Record<string, unknown>[]>>(
context: KeystoneContext,
initialData: T
) {
const results: any = {};
for (const listKey in initialData) {
results[listKey as keyof T] = await context.sudo().query[listKey].createMany({
data: initialData[listKey as keyof T],
});
}
return results as Record<keyof T, Record<string, unknown>[]>;
}
export const getPrismaSchema = async (_config: KeystoneConfig) => {
const config = initConfig(_config);
const { graphQLSchema } = createSystem(config);
const artifacts = await getCommittedArtifacts(graphQLSchema, config);
return artifacts.prisma;
};