@easy-cms/plugin-graphql 0.0.0-stage → 0.43.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/LICENSE +21 -0
- package/README.md +38 -2
- package/dist/index.d.ts +142 -0
- package/dist/index.js +1353 -0
- package/package.json +49 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,1353 @@
|
|
|
1
|
+
// src/context.ts
|
|
2
|
+
import {
|
|
3
|
+
ForbiddenError,
|
|
4
|
+
UnauthorizedError
|
|
5
|
+
} from "@easy-cms/core";
|
|
6
|
+
import DataLoader from "dataloader";
|
|
7
|
+
import { GraphQLError } from "graphql";
|
|
8
|
+
var DEFAULT_DOCUMENTS = 2e3;
|
|
9
|
+
var READ = /* @__PURE__ */ Symbol.for("easy-cms.graphql.read");
|
|
10
|
+
function tag(value, read) {
|
|
11
|
+
if (value && typeof value === "object")
|
|
12
|
+
Object.defineProperty(value, READ, { value: read, enumerable: false, configurable: true });
|
|
13
|
+
return value;
|
|
14
|
+
}
|
|
15
|
+
var readOf = (source) => source?.[READ] ?? {};
|
|
16
|
+
function toId(value) {
|
|
17
|
+
if (typeof value === "string" && /^[1-9]\d{0,15}$/.test(value)) {
|
|
18
|
+
const n = Number(value);
|
|
19
|
+
if (Number.isSafeInteger(n)) return n;
|
|
20
|
+
}
|
|
21
|
+
return value;
|
|
22
|
+
}
|
|
23
|
+
function createContext(cms, user, options = {}) {
|
|
24
|
+
const max = options.documents ?? DEFAULT_DOCUMENTS;
|
|
25
|
+
let loaded = 0;
|
|
26
|
+
const count = (documents) => {
|
|
27
|
+
loaded += documents;
|
|
28
|
+
if (loaded > max)
|
|
29
|
+
throw new GraphQLError(
|
|
30
|
+
`This query loads more than ${max} documents: ask for fewer, or raise limits.documents`,
|
|
31
|
+
{ extensions: { code: "QUERY_TOO_LARGE" } }
|
|
32
|
+
);
|
|
33
|
+
};
|
|
34
|
+
const loaders = /* @__PURE__ */ new Map();
|
|
35
|
+
const loaderFor = (collection, read) => {
|
|
36
|
+
const key = JSON.stringify([collection, read.locale, read.fallbackLocale, read.draft === true]);
|
|
37
|
+
let loader = loaders.get(key);
|
|
38
|
+
if (!loader) {
|
|
39
|
+
loader = new DataLoader(
|
|
40
|
+
async (ids) => {
|
|
41
|
+
let docs;
|
|
42
|
+
try {
|
|
43
|
+
const found = await cms.find(collection, {
|
|
44
|
+
user,
|
|
45
|
+
overrideAccess: false,
|
|
46
|
+
where: { id: { in: [...ids] } },
|
|
47
|
+
limit: 0,
|
|
48
|
+
depth: 0,
|
|
49
|
+
...read
|
|
50
|
+
});
|
|
51
|
+
docs = found.docs;
|
|
52
|
+
} catch (error) {
|
|
53
|
+
if (error instanceof ForbiddenError || error instanceof UnauthorizedError) docs = [];
|
|
54
|
+
else throw error;
|
|
55
|
+
}
|
|
56
|
+
count(docs.length);
|
|
57
|
+
const byId = new Map(docs.map((doc) => [String(doc.id), tag(doc, read)]));
|
|
58
|
+
return ids.map((id) => byId.get(String(id)) ?? null);
|
|
59
|
+
},
|
|
60
|
+
{ cacheKeyFn: (id) => String(id), maxBatchSize: 500 }
|
|
61
|
+
);
|
|
62
|
+
loaders.set(key, loader);
|
|
63
|
+
}
|
|
64
|
+
return loader;
|
|
65
|
+
};
|
|
66
|
+
return {
|
|
67
|
+
cms,
|
|
68
|
+
user,
|
|
69
|
+
count,
|
|
70
|
+
load: (collection, id, read = {}) => loaderFor(collection, read).load(id)
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// src/http.ts
|
|
75
|
+
import {
|
|
76
|
+
EasyCMSError,
|
|
77
|
+
ForbiddenError as ForbiddenError2,
|
|
78
|
+
NotFoundError,
|
|
79
|
+
UnauthorizedError as UnauthorizedError2,
|
|
80
|
+
ValidationError
|
|
81
|
+
} from "@easy-cms/core";
|
|
82
|
+
import {
|
|
83
|
+
execute,
|
|
84
|
+
getOperationAST,
|
|
85
|
+
NoSchemaIntrospectionCustomRule,
|
|
86
|
+
parse,
|
|
87
|
+
specifiedRules,
|
|
88
|
+
validate
|
|
89
|
+
} from "graphql";
|
|
90
|
+
|
|
91
|
+
// src/graphiql.ts
|
|
92
|
+
var GRAPHIQL = "graphiql@3.8.3";
|
|
93
|
+
var REACT = "18.3.1";
|
|
94
|
+
function graphiqlPage() {
|
|
95
|
+
return `<!doctype html>
|
|
96
|
+
<html lang="en">
|
|
97
|
+
<head>
|
|
98
|
+
<meta charset="utf-8">
|
|
99
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
100
|
+
<meta name="robots" content="noindex">
|
|
101
|
+
<title>GraphiQL \xB7 Easy CMS</title>
|
|
102
|
+
<link rel="stylesheet" href="https://unpkg.com/${GRAPHIQL}/graphiql.min.css">
|
|
103
|
+
<style>html, body, #graphiql { height: 100%; margin: 0; }</style>
|
|
104
|
+
</head>
|
|
105
|
+
<body>
|
|
106
|
+
<div id="graphiql">Loading GraphiQL\u2026</div>
|
|
107
|
+
<script crossorigin src="https://unpkg.com/react@${REACT}/umd/react.production.min.js"></script>
|
|
108
|
+
<script crossorigin src="https://unpkg.com/react-dom@${REACT}/umd/react-dom.production.min.js"></script>
|
|
109
|
+
<script crossorigin src="https://unpkg.com/${GRAPHIQL}/graphiql.min.js"></script>
|
|
110
|
+
<script>
|
|
111
|
+
const fetcher = GraphiQL.createFetcher({ url: location.pathname })
|
|
112
|
+
ReactDOM.createRoot(document.getElementById('graphiql')).render(
|
|
113
|
+
React.createElement(GraphiQL, {
|
|
114
|
+
fetcher,
|
|
115
|
+
defaultEditorToolsVisibility: true,
|
|
116
|
+
defaultQuery: '# Easy CMS GraphQL API. Ctrl+Space suggests fields; Ctrl+Enter runs.\\n{\\n me {\\n email\\n }\\n}\\n',
|
|
117
|
+
}),
|
|
118
|
+
)
|
|
119
|
+
</script>
|
|
120
|
+
</body>
|
|
121
|
+
</html>
|
|
122
|
+
`;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// src/limits.ts
|
|
126
|
+
import {
|
|
127
|
+
GraphQLError as GraphQLError2,
|
|
128
|
+
Kind
|
|
129
|
+
} from "graphql";
|
|
130
|
+
var DEFAULT_DEPTH = 7;
|
|
131
|
+
function depthOf(selections, fragments, visited) {
|
|
132
|
+
let deepest = 0;
|
|
133
|
+
for (const selection of selections.selections) {
|
|
134
|
+
if (selection.kind === Kind.FIELD) {
|
|
135
|
+
if (selection.name.value.startsWith("__")) continue;
|
|
136
|
+
const below = selection.selectionSet ? depthOf(selection.selectionSet, fragments, visited) : 0;
|
|
137
|
+
deepest = Math.max(deepest, 1 + below);
|
|
138
|
+
} else if (selection.kind === Kind.INLINE_FRAGMENT) {
|
|
139
|
+
deepest = Math.max(deepest, depthOf(selection.selectionSet, fragments, visited));
|
|
140
|
+
} else {
|
|
141
|
+
const name = selection.name.value;
|
|
142
|
+
const fragment = fragments.get(name);
|
|
143
|
+
if (!fragment || visited.has(name)) continue;
|
|
144
|
+
visited.add(name);
|
|
145
|
+
deepest = Math.max(deepest, depthOf(fragment.selectionSet, fragments, visited));
|
|
146
|
+
visited.delete(name);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
return deepest;
|
|
150
|
+
}
|
|
151
|
+
function depthLimit(max) {
|
|
152
|
+
return (context) => {
|
|
153
|
+
const fragments = new Map(
|
|
154
|
+
context.getDocument().definitions.filter((d) => d.kind === Kind.FRAGMENT_DEFINITION).map((d) => [d.name.value, d])
|
|
155
|
+
);
|
|
156
|
+
return {
|
|
157
|
+
OperationDefinition(node) {
|
|
158
|
+
const depth = depthOf(node.selectionSet, fragments, /* @__PURE__ */ new Set());
|
|
159
|
+
if (depth > max)
|
|
160
|
+
context.reportError(
|
|
161
|
+
new GraphQLError2(`This query is ${depth} levels deep; at most ${max} (limits.depth)`, {
|
|
162
|
+
nodes: node,
|
|
163
|
+
extensions: { code: "QUERY_TOO_DEEP" }
|
|
164
|
+
})
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
// src/http.ts
|
|
172
|
+
function codeOf(error) {
|
|
173
|
+
if (error instanceof ValidationError) return "VALIDATION_ERROR";
|
|
174
|
+
if (error instanceof UnauthorizedError2) return "UNAUTHORIZED";
|
|
175
|
+
if (error instanceof ForbiddenError2) return "FORBIDDEN";
|
|
176
|
+
if (error instanceof NotFoundError) return "NOT_FOUND";
|
|
177
|
+
switch (error.status) {
|
|
178
|
+
case 400:
|
|
179
|
+
return "BAD_REQUEST";
|
|
180
|
+
case 401:
|
|
181
|
+
return "UNAUTHORIZED";
|
|
182
|
+
case 403:
|
|
183
|
+
return "FORBIDDEN";
|
|
184
|
+
case 404:
|
|
185
|
+
return "NOT_FOUND";
|
|
186
|
+
case 413:
|
|
187
|
+
return "PAYLOAD_TOO_LARGE";
|
|
188
|
+
case 429:
|
|
189
|
+
return "TOO_MANY_REQUESTS";
|
|
190
|
+
default:
|
|
191
|
+
return "INTERNAL_SERVER_ERROR";
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
function formatError(error, cms) {
|
|
195
|
+
const original = error.originalError;
|
|
196
|
+
const base = {
|
|
197
|
+
message: error.message,
|
|
198
|
+
...error.locations ? { locations: error.locations } : {},
|
|
199
|
+
...error.path ? { path: error.path } : {}
|
|
200
|
+
};
|
|
201
|
+
if (original instanceof EasyCMSError && original.status < 500) {
|
|
202
|
+
return {
|
|
203
|
+
...base,
|
|
204
|
+
extensions: {
|
|
205
|
+
...error.extensions,
|
|
206
|
+
code: codeOf(original),
|
|
207
|
+
...original instanceof ValidationError ? { fields: original.errors } : {}
|
|
208
|
+
}
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
if (!original || original.extensions?.code) {
|
|
212
|
+
return {
|
|
213
|
+
...base,
|
|
214
|
+
...original ? { message: original.message } : {},
|
|
215
|
+
extensions: { ...error.extensions, ...original?.extensions }
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
cms.logger.error(`GraphQL: ${original.stack ?? original.message}`);
|
|
219
|
+
return {
|
|
220
|
+
...base,
|
|
221
|
+
message: process.env.NODE_ENV === "production" ? "Internal server error" : original.message,
|
|
222
|
+
extensions: { code: "INTERNAL_SERVER_ERROR" }
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function respond(body, status, request, headers = {}) {
|
|
226
|
+
const modern = request.headers.get("accept")?.includes("application/graphql-response+json");
|
|
227
|
+
return new Response(JSON.stringify(body), {
|
|
228
|
+
status,
|
|
229
|
+
headers: {
|
|
230
|
+
"content-type": `${modern ? "application/graphql-response+json" : "application/json"}; charset=utf-8`,
|
|
231
|
+
"cache-control": "no-store",
|
|
232
|
+
...headers
|
|
233
|
+
}
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
var requestError = (message, request, status = 400) => respond({ errors: [{ message, extensions: { code: "BAD_REQUEST" } }] }, status, request);
|
|
237
|
+
function fromSearchParams(url) {
|
|
238
|
+
const query = url.searchParams.get("query");
|
|
239
|
+
if (!query) return "Send a query: ?query={...}";
|
|
240
|
+
const variables = url.searchParams.get("variables");
|
|
241
|
+
let parsed = null;
|
|
242
|
+
if (variables) {
|
|
243
|
+
try {
|
|
244
|
+
parsed = JSON.parse(variables);
|
|
245
|
+
} catch {
|
|
246
|
+
return "variables must be JSON";
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return {
|
|
250
|
+
query,
|
|
251
|
+
variables: parsed,
|
|
252
|
+
operationName: url.searchParams.get("operationName")
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
function fromBody(body) {
|
|
256
|
+
if (typeof body.query !== "string" || !body.query) return 'Send { "query": "..." }';
|
|
257
|
+
if (body.variables !== void 0 && body.variables !== null && typeof body.variables !== "object")
|
|
258
|
+
return "variables must be an object";
|
|
259
|
+
if (body.operationName !== void 0 && body.operationName !== null && typeof body.operationName !== "string")
|
|
260
|
+
return "operationName must be a string";
|
|
261
|
+
return {
|
|
262
|
+
query: body.query,
|
|
263
|
+
variables: body.variables ?? null,
|
|
264
|
+
operationName: body.operationName ?? null
|
|
265
|
+
};
|
|
266
|
+
}
|
|
267
|
+
async function runGraphQL(cms, user, input, options, onlyQueries = false) {
|
|
268
|
+
let document;
|
|
269
|
+
try {
|
|
270
|
+
document = parse(input.query);
|
|
271
|
+
} catch (error) {
|
|
272
|
+
return { status: 400, body: { errors: [formatError(error, cms)] } };
|
|
273
|
+
}
|
|
274
|
+
const rules = [
|
|
275
|
+
...specifiedRules,
|
|
276
|
+
depthLimit(options.depth),
|
|
277
|
+
...options.introspection ? [] : [NoSchemaIntrospectionCustomRule]
|
|
278
|
+
];
|
|
279
|
+
const invalid = validate(options.schema, document, rules);
|
|
280
|
+
if (invalid.length > 0)
|
|
281
|
+
return { status: 400, body: { errors: invalid.map((e) => formatError(e, cms)) } };
|
|
282
|
+
if (onlyQueries) {
|
|
283
|
+
const operation = getOperationAST(document, input.operationName ?? void 0);
|
|
284
|
+
if (operation && operation.operation !== "query")
|
|
285
|
+
return {
|
|
286
|
+
status: 405,
|
|
287
|
+
allow: "POST",
|
|
288
|
+
body: {
|
|
289
|
+
errors: [
|
|
290
|
+
{
|
|
291
|
+
message: `Send ${operation.operation}s with POST`,
|
|
292
|
+
extensions: { code: "BAD_REQUEST" }
|
|
293
|
+
}
|
|
294
|
+
]
|
|
295
|
+
}
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
const result = await execute({
|
|
299
|
+
schema: options.schema,
|
|
300
|
+
document,
|
|
301
|
+
variableValues: input.variables ?? void 0,
|
|
302
|
+
operationName: input.operationName ?? void 0,
|
|
303
|
+
contextValue: createContext(cms, user, { documents: options.documents })
|
|
304
|
+
});
|
|
305
|
+
const body = {
|
|
306
|
+
...result.errors ? { errors: result.errors.map((e) => formatError(e, cms)) } : {},
|
|
307
|
+
..."data" in result ? { data: result.data } : {}
|
|
308
|
+
};
|
|
309
|
+
return { status: "data" in result && result.data !== void 0 ? 200 : 400, body };
|
|
310
|
+
}
|
|
311
|
+
async function handleGraphQL(args, options) {
|
|
312
|
+
const { request, url, user, cms } = args;
|
|
313
|
+
const get = request.method === "GET" || request.method === "HEAD";
|
|
314
|
+
if (get && !url.searchParams.has("query")) {
|
|
315
|
+
const browser = request.headers.get("accept")?.includes("text/html");
|
|
316
|
+
if (browser && options.graphiql)
|
|
317
|
+
return new Response(graphiqlPage(), {
|
|
318
|
+
headers: { "content-type": "text/html; charset=utf-8", "cache-control": "no-store" }
|
|
319
|
+
});
|
|
320
|
+
}
|
|
321
|
+
const input = get ? fromSearchParams(url) : fromBody(await args.json());
|
|
322
|
+
if (typeof input === "string") return requestError(input, request);
|
|
323
|
+
const { status, body, allow } = await runGraphQL(cms, user, input, options, get);
|
|
324
|
+
return respond(body, status, request, allow ? { allow } : {});
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
// src/plugin.ts
|
|
328
|
+
import { writeFile } from "fs/promises";
|
|
329
|
+
import { isAbsolute, resolve } from "path";
|
|
330
|
+
import {
|
|
331
|
+
API_KEYS as API_KEYS2,
|
|
332
|
+
definePlugin,
|
|
333
|
+
INTERNAL_COLLECTIONS as INTERNAL_COLLECTIONS2
|
|
334
|
+
} from "@easy-cms/core";
|
|
335
|
+
import { printSchema } from "graphql";
|
|
336
|
+
|
|
337
|
+
// src/info.ts
|
|
338
|
+
var INFO = {
|
|
339
|
+
name: "@easy-cms/plugin-graphql",
|
|
340
|
+
...true ? { version: "0.43.0" } : {}
|
|
341
|
+
};
|
|
342
|
+
|
|
343
|
+
// src/schema.ts
|
|
344
|
+
import {
|
|
345
|
+
API_KEYS,
|
|
346
|
+
INTERNAL_COLLECTIONS,
|
|
347
|
+
MEDIA,
|
|
348
|
+
MEDIA_FOLDERS
|
|
349
|
+
} from "@easy-cms/core";
|
|
350
|
+
import {
|
|
351
|
+
GraphQLBoolean,
|
|
352
|
+
GraphQLEnumType,
|
|
353
|
+
GraphQLError as GraphQLError4,
|
|
354
|
+
GraphQLFloat,
|
|
355
|
+
GraphQLID,
|
|
356
|
+
GraphQLInputObjectType,
|
|
357
|
+
GraphQLInt,
|
|
358
|
+
GraphQLList,
|
|
359
|
+
GraphQLNonNull,
|
|
360
|
+
GraphQLObjectType,
|
|
361
|
+
GraphQLSchema,
|
|
362
|
+
GraphQLString,
|
|
363
|
+
GraphQLUnionType
|
|
364
|
+
} from "graphql";
|
|
365
|
+
|
|
366
|
+
// src/names.ts
|
|
367
|
+
import { singularize } from "@easy-cms/core";
|
|
368
|
+
var VALID_NAME = /^[_A-Za-z][_0-9A-Za-z]*$/;
|
|
369
|
+
var isValidName = (name) => VALID_NAME.test(name) && !name.startsWith("__");
|
|
370
|
+
function pascal(name) {
|
|
371
|
+
return name.split(/[^A-Za-z0-9]+/).filter(Boolean).map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
|
|
372
|
+
}
|
|
373
|
+
function camel(name) {
|
|
374
|
+
const p = pascal(name);
|
|
375
|
+
return p.charAt(0).toLowerCase() + p.slice(1);
|
|
376
|
+
}
|
|
377
|
+
var BUILTIN = {
|
|
378
|
+
users: { type: "User", one: "user", many: "users" },
|
|
379
|
+
media: { type: "Media", one: "mediaItem", many: "media" },
|
|
380
|
+
"media-folders": { type: "MediaFolder", one: "mediaFolder", many: "mediaFolders" }
|
|
381
|
+
};
|
|
382
|
+
function collectionNames(slug, overrides = {}) {
|
|
383
|
+
const defaults = BUILTIN[slug] ?? {
|
|
384
|
+
type: pascal(singularize(slug)),
|
|
385
|
+
one: camel(singularize(slug)),
|
|
386
|
+
many: camel(slug)
|
|
387
|
+
};
|
|
388
|
+
return { ...defaults, ...overrides[slug] };
|
|
389
|
+
}
|
|
390
|
+
function globalNames(slug, overrides = {}) {
|
|
391
|
+
const own = overrides[slug];
|
|
392
|
+
return { type: own?.type ?? pascal(slug), one: own?.one ?? camel(slug) };
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
// src/scalars.ts
|
|
396
|
+
import { GraphQLError as GraphQLError3, GraphQLScalarType, Kind as Kind2 } from "graphql";
|
|
397
|
+
function literal(node, variables) {
|
|
398
|
+
switch (node.kind) {
|
|
399
|
+
case Kind2.STRING:
|
|
400
|
+
case Kind2.BOOLEAN:
|
|
401
|
+
case Kind2.ENUM:
|
|
402
|
+
return node.value;
|
|
403
|
+
case Kind2.INT:
|
|
404
|
+
case Kind2.FLOAT:
|
|
405
|
+
return Number(node.value);
|
|
406
|
+
case Kind2.NULL:
|
|
407
|
+
return null;
|
|
408
|
+
case Kind2.LIST:
|
|
409
|
+
return node.values.map((v) => literal(v, variables));
|
|
410
|
+
case Kind2.OBJECT:
|
|
411
|
+
return Object.fromEntries(node.fields.map((f) => [f.name.value, literal(f.value, variables)]));
|
|
412
|
+
case Kind2.VARIABLE:
|
|
413
|
+
return variables?.[node.name.value];
|
|
414
|
+
}
|
|
415
|
+
}
|
|
416
|
+
var JSONScalar = new GraphQLScalarType({
|
|
417
|
+
name: "JSON",
|
|
418
|
+
description: "Any JSON value: rich text documents (Tiptap JSON), json fields, block rows.",
|
|
419
|
+
serialize: (value) => value,
|
|
420
|
+
parseValue: (value) => value,
|
|
421
|
+
parseLiteral: (node, variables) => literal(node, variables)
|
|
422
|
+
});
|
|
423
|
+
var ISO_DATE = /^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:?\d{2})?)?$/;
|
|
424
|
+
function isoDate(value) {
|
|
425
|
+
if (typeof value === "string" && ISO_DATE.test(value) && !Number.isNaN(Date.parse(value)))
|
|
426
|
+
return value;
|
|
427
|
+
throw new GraphQLError3(`Not an ISO 8601 date: ${JSON.stringify(value)}`);
|
|
428
|
+
}
|
|
429
|
+
var DateTimeScalar = new GraphQLScalarType({
|
|
430
|
+
name: "DateTime",
|
|
431
|
+
description: "A date and time as an ISO 8601 string, e.g. 2026-10-08T09:30:00.000Z.",
|
|
432
|
+
serialize: (value) => value instanceof Date ? value.toISOString() : value,
|
|
433
|
+
parseValue: isoDate,
|
|
434
|
+
parseLiteral: (node) => {
|
|
435
|
+
if (node.kind !== Kind2.STRING) throw new GraphQLError3("DateTime must be a string");
|
|
436
|
+
return isoDate(node.value);
|
|
437
|
+
}
|
|
438
|
+
});
|
|
439
|
+
|
|
440
|
+
// src/schema.ts
|
|
441
|
+
var MAX_LIMIT = 100;
|
|
442
|
+
var RESERVED = /* @__PURE__ */ new Set([
|
|
443
|
+
"Query",
|
|
444
|
+
"Mutation",
|
|
445
|
+
"Subscription",
|
|
446
|
+
"String",
|
|
447
|
+
"Int",
|
|
448
|
+
"Float",
|
|
449
|
+
"Boolean",
|
|
450
|
+
"ID",
|
|
451
|
+
"JSON",
|
|
452
|
+
"DateTime",
|
|
453
|
+
"Locale",
|
|
454
|
+
"DocumentStatus",
|
|
455
|
+
"DocumentStatusFilter",
|
|
456
|
+
"StringFilter",
|
|
457
|
+
"FloatFilter",
|
|
458
|
+
"BooleanFilter",
|
|
459
|
+
"DateTimeFilter",
|
|
460
|
+
"IDFilter",
|
|
461
|
+
"MediaSize",
|
|
462
|
+
"MediaSizes"
|
|
463
|
+
]);
|
|
464
|
+
var MEDIA_SYSTEM_FIELDS = /* @__PURE__ */ new Set([
|
|
465
|
+
"filename",
|
|
466
|
+
"originalName",
|
|
467
|
+
"mimeType",
|
|
468
|
+
"filesize",
|
|
469
|
+
"width",
|
|
470
|
+
"height",
|
|
471
|
+
"sizes",
|
|
472
|
+
"private"
|
|
473
|
+
]);
|
|
474
|
+
var english = (label) => typeof label === "string" ? label : label?.en ?? Object.values(label ?? {})[0];
|
|
475
|
+
var describe = (label) => {
|
|
476
|
+
const text = english(label);
|
|
477
|
+
return text ? { description: text } : {};
|
|
478
|
+
};
|
|
479
|
+
var list = (type) => (
|
|
480
|
+
// biome-ignore lint/suspicious/noExplicitAny: as above
|
|
481
|
+
new GraphQLList(new GraphQLNonNull(type))
|
|
482
|
+
);
|
|
483
|
+
var hasMany = (field) => "hasMany" in field && field.hasMany === true;
|
|
484
|
+
var userError = (message) => new GraphQLError4(message, { extensions: { code: "BAD_USER_INPUT" } });
|
|
485
|
+
function exposedCollections(config, exclude = []) {
|
|
486
|
+
return config.collections.filter(
|
|
487
|
+
(c) => !INTERNAL_COLLECTIONS.has(c.slug) && c.slug !== API_KEYS && !exclude.includes(c.slug)
|
|
488
|
+
);
|
|
489
|
+
}
|
|
490
|
+
function checkNames(collections, globals, overrides = {}) {
|
|
491
|
+
const problems = [];
|
|
492
|
+
const types = /* @__PURE__ */ new Map();
|
|
493
|
+
const queries = /* @__PURE__ */ new Map([["me", "the current user"]]);
|
|
494
|
+
const mutations = /* @__PURE__ */ new Map();
|
|
495
|
+
const claim = (map, kind, name, owner) => {
|
|
496
|
+
if (!isValidName(name)) {
|
|
497
|
+
problems.push(`${owner}: "${name}" is not a valid GraphQL name`);
|
|
498
|
+
return;
|
|
499
|
+
}
|
|
500
|
+
if (kind === "type" && RESERVED.has(name)) {
|
|
501
|
+
problems.push(`${owner}: the type name "${name}" is taken by the schema`);
|
|
502
|
+
return;
|
|
503
|
+
}
|
|
504
|
+
const other = map.get(name);
|
|
505
|
+
if (other) problems.push(`${owner}: the ${kind} name "${name}" is also used by ${other}`);
|
|
506
|
+
else map.set(name, owner);
|
|
507
|
+
};
|
|
508
|
+
const byCollection = /* @__PURE__ */ new Map();
|
|
509
|
+
for (const slug of collections) {
|
|
510
|
+
const names = collectionNames(slug, overrides);
|
|
511
|
+
const owner = `collection "${slug}"`;
|
|
512
|
+
byCollection.set(slug, names);
|
|
513
|
+
claim(types, "type", names.type, owner);
|
|
514
|
+
claim(queries, "query", names.one, owner);
|
|
515
|
+
claim(queries, "query", names.many, owner);
|
|
516
|
+
for (const verb of ["create", "update", "delete"])
|
|
517
|
+
claim(mutations, "mutation", `${verb}${names.type}`, owner);
|
|
518
|
+
}
|
|
519
|
+
const byGlobal = /* @__PURE__ */ new Map();
|
|
520
|
+
for (const slug of globals) {
|
|
521
|
+
const names = globalNames(slug, overrides);
|
|
522
|
+
const owner = `global "${slug}"`;
|
|
523
|
+
byGlobal.set(slug, names);
|
|
524
|
+
claim(types, "type", names.type, owner);
|
|
525
|
+
claim(queries, "query", names.one, owner);
|
|
526
|
+
claim(mutations, "mutation", `update${names.type}`, owner);
|
|
527
|
+
}
|
|
528
|
+
if (problems.length > 0) {
|
|
529
|
+
const example = collections[0] ?? globals[0] ?? "news";
|
|
530
|
+
throw new Error(
|
|
531
|
+
`graphqlPlugin: names in the schema clash:
|
|
532
|
+
${problems.map((p) => ` \u2022 ${p}`).join("\n")}
|
|
533
|
+
\u2192 Choose other names, e.g. graphqlPlugin({ names: { '${example}': { type: 'NewsItem', one: 'newsItem', many: 'news' } } })`
|
|
534
|
+
);
|
|
535
|
+
}
|
|
536
|
+
return { collections: byCollection, globals: byGlobal };
|
|
537
|
+
}
|
|
538
|
+
function textToDoc(text) {
|
|
539
|
+
const paragraphs = text.split(/\n\s*\n/).map((p) => p.trim()).filter(Boolean);
|
|
540
|
+
return {
|
|
541
|
+
type: "doc",
|
|
542
|
+
content: paragraphs.map((paragraph) => ({
|
|
543
|
+
type: "paragraph",
|
|
544
|
+
content: paragraph.split("\n").flatMap((line, i) => [
|
|
545
|
+
...i > 0 ? [{ type: "hardBreak" }] : [],
|
|
546
|
+
...line ? [{ type: "text", text: line }] : []
|
|
547
|
+
])
|
|
548
|
+
}))
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
var idOf = (value) => value && typeof value === "object" ? value.id : value;
|
|
552
|
+
function buildGraphQLSchema(config, options = {}) {
|
|
553
|
+
return new Builder(config, options).schema();
|
|
554
|
+
}
|
|
555
|
+
var Builder = class {
|
|
556
|
+
constructor(config, options) {
|
|
557
|
+
this.config = config;
|
|
558
|
+
this.options = options;
|
|
559
|
+
const exclude = options.exclude ?? [];
|
|
560
|
+
this.collections = exposedCollections(config, exclude);
|
|
561
|
+
this.globals = config.globals.filter((g) => !exclude.includes(g.slug));
|
|
562
|
+
this.names = checkNames(
|
|
563
|
+
this.collections.map((c) => c.slug),
|
|
564
|
+
this.globals.map((g) => g.slug),
|
|
565
|
+
options.names
|
|
566
|
+
);
|
|
567
|
+
for (const names of [...this.names.collections.values(), ...this.names.globals.values()])
|
|
568
|
+
this.taken.add(names.type);
|
|
569
|
+
const locales = config.localization?.locales ?? [];
|
|
570
|
+
this.locale = locales.length ? new GraphQLEnumType({
|
|
571
|
+
name: "Locale",
|
|
572
|
+
values: Object.fromEntries(
|
|
573
|
+
locales.map((l) => [
|
|
574
|
+
l.replace(/[^_0-9A-Za-z]/g, "_").replace(/^(\d)/, "_$1"),
|
|
575
|
+
{ value: l }
|
|
576
|
+
])
|
|
577
|
+
)
|
|
578
|
+
}) : void 0;
|
|
579
|
+
const filter = (name, type, ordered) => new GraphQLInputObjectType({
|
|
580
|
+
name,
|
|
581
|
+
fields: {
|
|
582
|
+
equals: { type },
|
|
583
|
+
not_equals: { type },
|
|
584
|
+
...type === GraphQLBoolean ? {} : { in: { type: list(type) }, not_in: { type: list(type) } },
|
|
585
|
+
...ordered ? { gt: { type }, gte: { type }, lt: { type }, lte: { type } } : {},
|
|
586
|
+
...type === GraphQLString ? { like: { type: GraphQLString } } : {},
|
|
587
|
+
exists: { type: GraphQLBoolean }
|
|
588
|
+
}
|
|
589
|
+
});
|
|
590
|
+
this.filters = {
|
|
591
|
+
String: filter("StringFilter", GraphQLString, false),
|
|
592
|
+
Float: filter("FloatFilter", GraphQLFloat, true),
|
|
593
|
+
Boolean: filter("BooleanFilter", GraphQLBoolean, false),
|
|
594
|
+
DateTime: filter("DateTimeFilter", DateTimeScalar, true),
|
|
595
|
+
ID: filter("IDFilter", GraphQLID, false),
|
|
596
|
+
status: filter("DocumentStatusFilter", this.status, false)
|
|
597
|
+
};
|
|
598
|
+
}
|
|
599
|
+
config;
|
|
600
|
+
options;
|
|
601
|
+
collections;
|
|
602
|
+
globals;
|
|
603
|
+
names;
|
|
604
|
+
taken = new Set(RESERVED);
|
|
605
|
+
objects = /* @__PURE__ */ new Map();
|
|
606
|
+
extra = /* @__PURE__ */ new Map();
|
|
607
|
+
blockTypes = /* @__PURE__ */ new Map();
|
|
608
|
+
locale;
|
|
609
|
+
status = new GraphQLEnumType({
|
|
610
|
+
name: "DocumentStatus",
|
|
611
|
+
values: { draft: { value: "draft" }, published: { value: "published" } }
|
|
612
|
+
});
|
|
613
|
+
filters;
|
|
614
|
+
/** A type name of its own: `PostSeo`, else `PostSeo2`… */
|
|
615
|
+
claim(name) {
|
|
616
|
+
let unique = name;
|
|
617
|
+
for (let n = 2; this.taken.has(unique); n++) unique = `${name}${n}`;
|
|
618
|
+
this.taken.add(unique);
|
|
619
|
+
return unique;
|
|
620
|
+
}
|
|
621
|
+
exposed(slug) {
|
|
622
|
+
return this.names.collections.has(slug);
|
|
623
|
+
}
|
|
624
|
+
schema() {
|
|
625
|
+
for (const c of this.collections) {
|
|
626
|
+
const { type } = this.names.collections.get(c.slug);
|
|
627
|
+
this.objects.set(c.slug, this.collectionType(c, type));
|
|
628
|
+
}
|
|
629
|
+
const globalTypes = /* @__PURE__ */ new Map();
|
|
630
|
+
for (const g of this.globals) {
|
|
631
|
+
const { type } = this.names.globals.get(g.slug);
|
|
632
|
+
globalTypes.set(g.slug, this.globalType(g, type));
|
|
633
|
+
}
|
|
634
|
+
const query = {};
|
|
635
|
+
const mutation = {};
|
|
636
|
+
for (const c of this.collections) this.collectionOperations(c, query, mutation);
|
|
637
|
+
for (const g of this.globals)
|
|
638
|
+
this.globalOperations(g, globalTypes.get(g.slug), query, mutation);
|
|
639
|
+
const users = this.objects.get("users");
|
|
640
|
+
if (users) {
|
|
641
|
+
query.me = {
|
|
642
|
+
type: users,
|
|
643
|
+
description: "The logged-in user (or the owner of the API key), or null.",
|
|
644
|
+
resolve: (_source, _args, ctx) => ctx.user ? ctx.load("users", ctx.user.id) : null
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
if (this.options.extend) {
|
|
648
|
+
const types = Object.fromEntries(
|
|
649
|
+
[...this.objects.values(), ...globalTypes.values()].map((t) => [t.name, t])
|
|
650
|
+
);
|
|
651
|
+
const extension = this.options.extend({
|
|
652
|
+
config: this.config,
|
|
653
|
+
types,
|
|
654
|
+
type: (name) => {
|
|
655
|
+
const found = types[name];
|
|
656
|
+
if (!found)
|
|
657
|
+
throw new Error(`graphqlPlugin: extend asks for the type "${name}", which is not here`);
|
|
658
|
+
return found;
|
|
659
|
+
},
|
|
660
|
+
scalars: { JSON: JSONScalar, DateTime: DateTimeScalar }
|
|
661
|
+
});
|
|
662
|
+
for (const [typeName, fields] of Object.entries(extension.fields ?? {})) {
|
|
663
|
+
if (!types[typeName])
|
|
664
|
+
throw new Error(
|
|
665
|
+
`graphqlPlugin: extend adds fields to "${typeName}", which is not a type here`
|
|
666
|
+
);
|
|
667
|
+
this.extra.set(typeName, { ...this.extra.get(typeName), ...fields });
|
|
668
|
+
}
|
|
669
|
+
const add = (target, more, kind) => {
|
|
670
|
+
for (const [name, field] of Object.entries(more ?? {})) {
|
|
671
|
+
if (target[name])
|
|
672
|
+
throw new Error(`graphqlPlugin: extend adds the ${kind} "${name}", which exists`);
|
|
673
|
+
target[name] = field;
|
|
674
|
+
}
|
|
675
|
+
};
|
|
676
|
+
add(query, extension.query, "query");
|
|
677
|
+
add(mutation, extension.mutation, "mutation");
|
|
678
|
+
}
|
|
679
|
+
return new GraphQLSchema({
|
|
680
|
+
query: new GraphQLObjectType({ name: "Query", fields: query }),
|
|
681
|
+
...Object.keys(mutation).length ? { mutation: new GraphQLObjectType({ name: "Mutation", fields: mutation }) } : {}
|
|
682
|
+
});
|
|
683
|
+
}
|
|
684
|
+
// ---- Reading -------------------------------------------------------------------------------
|
|
685
|
+
/** `locale` and `fallbackLocale` arguments, with localization. */
|
|
686
|
+
localeArgs() {
|
|
687
|
+
return this.locale ? {
|
|
688
|
+
locale: {
|
|
689
|
+
type: this.locale,
|
|
690
|
+
description: "Content language. Default: the default locale."
|
|
691
|
+
},
|
|
692
|
+
fallbackLocale: {
|
|
693
|
+
type: GraphQLBoolean,
|
|
694
|
+
description: "Use the default locale's value when a value is empty."
|
|
695
|
+
}
|
|
696
|
+
} : {};
|
|
697
|
+
}
|
|
698
|
+
readArgs(drafts) {
|
|
699
|
+
return {
|
|
700
|
+
...this.localeArgs(),
|
|
701
|
+
...drafts ? {
|
|
702
|
+
draft: {
|
|
703
|
+
type: GraphQLBoolean,
|
|
704
|
+
description: "Include drafts (logged-in users and API keys only)."
|
|
705
|
+
}
|
|
706
|
+
} : {}
|
|
707
|
+
};
|
|
708
|
+
}
|
|
709
|
+
collectionType(c, name) {
|
|
710
|
+
const media = c.slug === MEDIA;
|
|
711
|
+
return new GraphQLObjectType({
|
|
712
|
+
name,
|
|
713
|
+
...describe(c.labels?.singular),
|
|
714
|
+
fields: () => {
|
|
715
|
+
const fields = {
|
|
716
|
+
id: { type: new GraphQLNonNull(GraphQLID) },
|
|
717
|
+
...this.outputFields(media ? c.fields.filter((f) => f.name !== "sizes") : c.fields, name)
|
|
718
|
+
};
|
|
719
|
+
if (media) {
|
|
720
|
+
fields.url = { type: GraphQLString, description: "Where the file is served." };
|
|
721
|
+
const sizes = this.mediaSizes();
|
|
722
|
+
if (sizes) fields.sizes = { type: sizes, description: "Resized copies of images." };
|
|
723
|
+
}
|
|
724
|
+
if (c.slug === MEDIA_FOLDERS)
|
|
725
|
+
fields.level = {
|
|
726
|
+
type: GraphQLString,
|
|
727
|
+
description: "What you may do in this folder: view, edit or manage."
|
|
728
|
+
};
|
|
729
|
+
if (c.drafts) fields.status = { type: this.status };
|
|
730
|
+
fields.createdAt = { type: new GraphQLNonNull(DateTimeScalar) };
|
|
731
|
+
fields.updatedAt = { type: new GraphQLNonNull(DateTimeScalar) };
|
|
732
|
+
return { ...fields, ...this.extra.get(name) };
|
|
733
|
+
}
|
|
734
|
+
});
|
|
735
|
+
}
|
|
736
|
+
globalType(g, name) {
|
|
737
|
+
return new GraphQLObjectType({
|
|
738
|
+
name,
|
|
739
|
+
...describe(g.label),
|
|
740
|
+
fields: () => ({
|
|
741
|
+
...this.outputFields(g.fields, name),
|
|
742
|
+
...g.drafts ? { status: { type: this.status } } : {},
|
|
743
|
+
updatedAt: {
|
|
744
|
+
type: DateTimeScalar,
|
|
745
|
+
description: "Null until the global is saved for the first time."
|
|
746
|
+
},
|
|
747
|
+
...this.extra.get(name)
|
|
748
|
+
})
|
|
749
|
+
});
|
|
750
|
+
}
|
|
751
|
+
mediaSizeTypes;
|
|
752
|
+
/** `sizes { thumbnail { url width height } }`, from `upload.imageSizes`. */
|
|
753
|
+
mediaSizes() {
|
|
754
|
+
if (this.mediaSizeTypes !== void 0) return this.mediaSizeTypes;
|
|
755
|
+
const names = (this.config.upload.imageSizes ?? []).map((s) => s.name).filter(isValidName);
|
|
756
|
+
if (names.length === 0) {
|
|
757
|
+
this.mediaSizeTypes = null;
|
|
758
|
+
return null;
|
|
759
|
+
}
|
|
760
|
+
const size = new GraphQLObjectType({
|
|
761
|
+
name: "MediaSize",
|
|
762
|
+
fields: {
|
|
763
|
+
filename: { type: GraphQLString },
|
|
764
|
+
url: { type: GraphQLString },
|
|
765
|
+
width: { type: GraphQLInt },
|
|
766
|
+
height: { type: GraphQLInt }
|
|
767
|
+
}
|
|
768
|
+
});
|
|
769
|
+
this.mediaSizeTypes = new GraphQLObjectType({
|
|
770
|
+
name: "MediaSizes",
|
|
771
|
+
fields: Object.fromEntries(names.map((n) => [n, { type: size }]))
|
|
772
|
+
});
|
|
773
|
+
return this.mediaSizeTypes;
|
|
774
|
+
}
|
|
775
|
+
outputFields(fields, path) {
|
|
776
|
+
const out = {};
|
|
777
|
+
for (const field of fields) {
|
|
778
|
+
if (field.hidden || !isValidName(field.name)) continue;
|
|
779
|
+
out[field.name] = { ...describe(field.label), ...this.outputField(field, path) };
|
|
780
|
+
}
|
|
781
|
+
return out;
|
|
782
|
+
}
|
|
783
|
+
outputField(field, path) {
|
|
784
|
+
const many = (type) => hasMany(field) ? list(type) : type;
|
|
785
|
+
switch (field.type) {
|
|
786
|
+
case "number":
|
|
787
|
+
return { type: GraphQLFloat };
|
|
788
|
+
case "boolean":
|
|
789
|
+
return { type: GraphQLBoolean };
|
|
790
|
+
case "date":
|
|
791
|
+
return { type: DateTimeScalar };
|
|
792
|
+
case "json":
|
|
793
|
+
case "richText":
|
|
794
|
+
return { type: JSONScalar };
|
|
795
|
+
case "select":
|
|
796
|
+
return { type: many(this.selectType(field, path) ?? GraphQLString) };
|
|
797
|
+
case "relationship":
|
|
798
|
+
case "upload":
|
|
799
|
+
return this.relationField(field);
|
|
800
|
+
case "group": {
|
|
801
|
+
const type = new GraphQLObjectType({
|
|
802
|
+
name: this.claim(`${path}${pascal(field.name)}`),
|
|
803
|
+
fields: () => this.outputFields(field.fields, `${path}${pascal(field.name)}`)
|
|
804
|
+
});
|
|
805
|
+
return {
|
|
806
|
+
type,
|
|
807
|
+
resolve: (source) => tag(source[field.name] ?? null, readOf(source))
|
|
808
|
+
};
|
|
809
|
+
}
|
|
810
|
+
case "array": {
|
|
811
|
+
const name = this.claim(`${path}${pascal(field.name)}Row`);
|
|
812
|
+
const type = new GraphQLObjectType({
|
|
813
|
+
name,
|
|
814
|
+
fields: () => ({ id: { type: GraphQLString }, ...this.outputFields(field.fields, name) })
|
|
815
|
+
});
|
|
816
|
+
return { type: list(type), resolve: (source) => this.rows(source, field.name) };
|
|
817
|
+
}
|
|
818
|
+
case "blocks": {
|
|
819
|
+
const members = field.blocks.map((block) => this.blockType(block, path));
|
|
820
|
+
const union = new GraphQLUnionType({
|
|
821
|
+
name: this.claim(`${path}${pascal(field.name)}Block`),
|
|
822
|
+
types: members,
|
|
823
|
+
resolveType: (row) => members[field.blocks.findIndex((b) => b.slug === row.blockType)]?.name
|
|
824
|
+
});
|
|
825
|
+
return {
|
|
826
|
+
type: list(union),
|
|
827
|
+
resolve: (source) => this.rows(source, field.name).filter(
|
|
828
|
+
(row) => field.blocks.some((b) => b.slug === row.blockType)
|
|
829
|
+
)
|
|
830
|
+
};
|
|
831
|
+
}
|
|
832
|
+
default:
|
|
833
|
+
return { type: GraphQLString };
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
rows(source, name) {
|
|
837
|
+
const value = source[name];
|
|
838
|
+
const read = readOf(source);
|
|
839
|
+
return Array.isArray(value) ? value.map((row) => tag(row, read)) : [];
|
|
840
|
+
}
|
|
841
|
+
/** A block's type: shared by the fields that use the same block object (`HeroBlock`). */
|
|
842
|
+
blockType(block, path) {
|
|
843
|
+
const known = this.blockTypes.get(block);
|
|
844
|
+
if (known) return known;
|
|
845
|
+
const base = `${pascal(block.slug)}Block`;
|
|
846
|
+
const name = this.claim(this.taken.has(base) ? `${path}${base}` : base);
|
|
847
|
+
const type = new GraphQLObjectType({
|
|
848
|
+
name,
|
|
849
|
+
...describe(block.labels?.singular),
|
|
850
|
+
fields: () => ({
|
|
851
|
+
id: { type: GraphQLString },
|
|
852
|
+
blockType: { type: new GraphQLNonNull(GraphQLString) },
|
|
853
|
+
...this.outputFields(block.fields, name)
|
|
854
|
+
})
|
|
855
|
+
});
|
|
856
|
+
this.blockTypes.set(block, type);
|
|
857
|
+
return type;
|
|
858
|
+
}
|
|
859
|
+
selectEnums = /* @__PURE__ */ new Map();
|
|
860
|
+
/** An enum of the options, when every value is a valid GraphQL name. */
|
|
861
|
+
selectType(field, path) {
|
|
862
|
+
if (this.selectEnums.has(field)) return this.selectEnums.get(field) ?? null;
|
|
863
|
+
const values = field.options.map((o) => typeof o === "string" ? o : o.value);
|
|
864
|
+
const valid = values.length > 0 && values.every((v) => isValidName(v) && v !== "true" && v !== "false" && v !== "null");
|
|
865
|
+
const type = valid ? new GraphQLEnumType({
|
|
866
|
+
name: this.claim(`${path}${pascal(field.name)}`),
|
|
867
|
+
values: Object.fromEntries(values.map((v) => [v, { value: v }]))
|
|
868
|
+
}) : null;
|
|
869
|
+
this.selectEnums.set(field, type);
|
|
870
|
+
return type;
|
|
871
|
+
}
|
|
872
|
+
relationField(field) {
|
|
873
|
+
const target = field.type === "upload" ? MEDIA : field.to;
|
|
874
|
+
const many = hasMany(field);
|
|
875
|
+
const type = this.objects.get(target);
|
|
876
|
+
if (!type || !this.exposed(target)) {
|
|
877
|
+
return {
|
|
878
|
+
type: many ? list(GraphQLID) : GraphQLID,
|
|
879
|
+
resolve: (source) => {
|
|
880
|
+
const value = source[field.name];
|
|
881
|
+
if (value === null || value === void 0) return many ? [] : null;
|
|
882
|
+
return Array.isArray(value) ? value.map(idOf) : idOf(value);
|
|
883
|
+
}
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
return {
|
|
887
|
+
type: many ? list(type) : type,
|
|
888
|
+
args: this.localeArgs(),
|
|
889
|
+
resolve: async (source, args, ctx) => {
|
|
890
|
+
const read = { ...readOf(source), ...this.localeOf(args) };
|
|
891
|
+
const value = source[field.name];
|
|
892
|
+
if (value === null || value === void 0) return many ? [] : null;
|
|
893
|
+
const ids = (Array.isArray(value) ? value : [value]).map(idOf);
|
|
894
|
+
const docs = await Promise.all(
|
|
895
|
+
ids.map(
|
|
896
|
+
(id) => id === null || id === void 0 ? null : ctx.load(target, toId(id), read)
|
|
897
|
+
)
|
|
898
|
+
);
|
|
899
|
+
return many ? docs.filter((d) => d !== null) : docs[0] ?? null;
|
|
900
|
+
}
|
|
901
|
+
};
|
|
902
|
+
}
|
|
903
|
+
localeOf(args) {
|
|
904
|
+
return {
|
|
905
|
+
...typeof args.locale === "string" ? { locale: args.locale } : {},
|
|
906
|
+
...typeof args.fallbackLocale === "boolean" ? { fallbackLocale: args.fallbackLocale } : {}
|
|
907
|
+
};
|
|
908
|
+
}
|
|
909
|
+
/** What a query asked for: drafts only for logged-in users and API keys, as in REST. */
|
|
910
|
+
readOf(args, ctx) {
|
|
911
|
+
return { ...this.localeOf(args), ...args.draft === true && ctx.user ? { draft: true } : {} };
|
|
912
|
+
}
|
|
913
|
+
// ---- Filtering and sorting -----------------------------------------------------------------
|
|
914
|
+
whereType(fields, name, drafts, root) {
|
|
915
|
+
const type = new GraphQLInputObjectType({
|
|
916
|
+
name: this.claim(`${name}Where`),
|
|
917
|
+
fields: () => {
|
|
918
|
+
const out = {};
|
|
919
|
+
if (root) {
|
|
920
|
+
out.id = { type: this.filters.ID };
|
|
921
|
+
out.createdAt = { type: this.filters.DateTime };
|
|
922
|
+
out.updatedAt = { type: this.filters.DateTime };
|
|
923
|
+
if (drafts) out.status = { type: this.filters.status };
|
|
924
|
+
}
|
|
925
|
+
for (const field of fields) {
|
|
926
|
+
if (field.hidden || !isValidName(field.name)) continue;
|
|
927
|
+
const filter = this.filterOf(field, name);
|
|
928
|
+
if (filter) out[field.name] = { type: filter };
|
|
929
|
+
}
|
|
930
|
+
if (root) {
|
|
931
|
+
out.AND = { type: list(type) };
|
|
932
|
+
out.OR = { type: list(type) };
|
|
933
|
+
}
|
|
934
|
+
return out;
|
|
935
|
+
}
|
|
936
|
+
});
|
|
937
|
+
return type;
|
|
938
|
+
}
|
|
939
|
+
enumFilters = /* @__PURE__ */ new Map();
|
|
940
|
+
filterOf(field, path) {
|
|
941
|
+
switch (field.type) {
|
|
942
|
+
case "text":
|
|
943
|
+
case "textarea":
|
|
944
|
+
case "email":
|
|
945
|
+
case "slug":
|
|
946
|
+
return this.filters.String;
|
|
947
|
+
case "number":
|
|
948
|
+
return this.filters.Float;
|
|
949
|
+
case "boolean":
|
|
950
|
+
return this.filters.Boolean;
|
|
951
|
+
case "date":
|
|
952
|
+
return this.filters.DateTime;
|
|
953
|
+
case "relationship":
|
|
954
|
+
case "upload":
|
|
955
|
+
return this.filters.ID;
|
|
956
|
+
case "select": {
|
|
957
|
+
const type = this.selectType(field, path);
|
|
958
|
+
if (!type) return this.filters.String;
|
|
959
|
+
let filter = this.enumFilters.get(type);
|
|
960
|
+
if (!filter) {
|
|
961
|
+
filter = new GraphQLInputObjectType({
|
|
962
|
+
name: this.claim(`${type.name}Filter`),
|
|
963
|
+
fields: {
|
|
964
|
+
equals: { type },
|
|
965
|
+
not_equals: { type },
|
|
966
|
+
in: { type: list(type) },
|
|
967
|
+
not_in: { type: list(type) },
|
|
968
|
+
exists: { type: GraphQLBoolean }
|
|
969
|
+
}
|
|
970
|
+
});
|
|
971
|
+
this.enumFilters.set(type, filter);
|
|
972
|
+
}
|
|
973
|
+
return filter;
|
|
974
|
+
}
|
|
975
|
+
case "group":
|
|
976
|
+
return this.whereType(field.fields, `${path}${pascal(field.name)}`, false, false);
|
|
977
|
+
default:
|
|
978
|
+
return field.type === "json" || field.type === "richText" || field.type === "array" || field.type === "blocks" ? void 0 : this.filters.String;
|
|
979
|
+
}
|
|
980
|
+
}
|
|
981
|
+
sortType(c, name) {
|
|
982
|
+
const sortable = c.fields.filter(
|
|
983
|
+
(f) => !f.hidden && isValidName(f.name) && !hasMany(f) && ["text", "textarea", "email", "slug", "number", "date", "boolean", "select"].includes(
|
|
984
|
+
f.type
|
|
985
|
+
)
|
|
986
|
+
);
|
|
987
|
+
const values = {};
|
|
988
|
+
for (const field of ["id", ...sortable.map((f) => f.name), "createdAt", "updatedAt"]) {
|
|
989
|
+
values[`${field}_ASC`] = { value: field };
|
|
990
|
+
values[`${field}_DESC`] = { value: `-${field}` };
|
|
991
|
+
}
|
|
992
|
+
return new GraphQLEnumType({ name: this.claim(`${name}Sort`), values });
|
|
993
|
+
}
|
|
994
|
+
// ---- Operations ----------------------------------------------------------------------------
|
|
995
|
+
collectionOperations(c, query, mutation) {
|
|
996
|
+
const slug = c.slug;
|
|
997
|
+
const names = this.names.collections.get(slug);
|
|
998
|
+
const type = this.objects.get(slug);
|
|
999
|
+
const drafts = c.drafts === true;
|
|
1000
|
+
const where = this.whereType(c.fields, names.type, drafts, true);
|
|
1001
|
+
const access = (ctx) => ({ user: ctx.user, overrideAccess: false });
|
|
1002
|
+
query[names.one] = {
|
|
1003
|
+
type,
|
|
1004
|
+
...describe(c.labels?.singular),
|
|
1005
|
+
args: { id: { type: new GraphQLNonNull(GraphQLID) }, ...this.readArgs(drafts) },
|
|
1006
|
+
resolve: async (_source, args, ctx) => {
|
|
1007
|
+
const read = this.readOf(args, ctx);
|
|
1008
|
+
const doc = await ctx.cms.findById(slug, toId(args.id), {
|
|
1009
|
+
...access(ctx),
|
|
1010
|
+
depth: 0,
|
|
1011
|
+
...read
|
|
1012
|
+
});
|
|
1013
|
+
if (doc) ctx.count(1);
|
|
1014
|
+
return tag(doc, read);
|
|
1015
|
+
}
|
|
1016
|
+
};
|
|
1017
|
+
const page = new GraphQLObjectType({
|
|
1018
|
+
name: this.claim(`${names.type}List`),
|
|
1019
|
+
fields: {
|
|
1020
|
+
docs: { type: new GraphQLNonNull(list(type)) },
|
|
1021
|
+
totalDocs: { type: new GraphQLNonNull(GraphQLInt) },
|
|
1022
|
+
limit: { type: new GraphQLNonNull(GraphQLInt) },
|
|
1023
|
+
page: { type: new GraphQLNonNull(GraphQLInt) },
|
|
1024
|
+
totalPages: { type: new GraphQLNonNull(GraphQLInt) },
|
|
1025
|
+
hasNextPage: { type: new GraphQLNonNull(GraphQLBoolean) },
|
|
1026
|
+
hasPrevPage: { type: new GraphQLNonNull(GraphQLBoolean) }
|
|
1027
|
+
}
|
|
1028
|
+
});
|
|
1029
|
+
const fields = c.fields;
|
|
1030
|
+
query[names.many] = {
|
|
1031
|
+
type: new GraphQLNonNull(page),
|
|
1032
|
+
...describe(c.labels?.plural),
|
|
1033
|
+
args: {
|
|
1034
|
+
where: { type: where },
|
|
1035
|
+
sort: { type: list(this.sortType(c, names.type)) },
|
|
1036
|
+
limit: { type: GraphQLInt, defaultValue: 10, description: `1 to ${MAX_LIMIT}.` },
|
|
1037
|
+
page: { type: GraphQLInt, defaultValue: 1 },
|
|
1038
|
+
...this.readArgs(drafts)
|
|
1039
|
+
},
|
|
1040
|
+
resolve: async (_source, args, ctx) => {
|
|
1041
|
+
const limit = args.limit;
|
|
1042
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT)
|
|
1043
|
+
throw userError(`limit must be between 1 and ${MAX_LIMIT}`);
|
|
1044
|
+
const read = this.readOf(args, ctx);
|
|
1045
|
+
const result = await ctx.cms.find(slug, {
|
|
1046
|
+
...access(ctx),
|
|
1047
|
+
depth: 0,
|
|
1048
|
+
limit,
|
|
1049
|
+
page: args.page,
|
|
1050
|
+
...args.where ? { where: toWhere(args.where, fields) } : {},
|
|
1051
|
+
...Array.isArray(args.sort) && args.sort.length ? { sort: args.sort } : {},
|
|
1052
|
+
...read
|
|
1053
|
+
});
|
|
1054
|
+
ctx.count(result.docs.length);
|
|
1055
|
+
return { ...result, docs: result.docs.map((d) => tag(d, read)) };
|
|
1056
|
+
}
|
|
1057
|
+
};
|
|
1058
|
+
const written = (doc, args) => tag(doc, this.localeOf(args));
|
|
1059
|
+
const status = (data, args) => drafts && typeof args.draft === "boolean" ? { ...data, status: args.draft ? "draft" : "published" } : data;
|
|
1060
|
+
const writeArgs = {
|
|
1061
|
+
...this.localeArgsForWrite(),
|
|
1062
|
+
...drafts ? {
|
|
1063
|
+
draft: {
|
|
1064
|
+
type: GraphQLBoolean,
|
|
1065
|
+
description: "true: save as a draft. false: publish. Default: as the collection does."
|
|
1066
|
+
}
|
|
1067
|
+
} : {}
|
|
1068
|
+
};
|
|
1069
|
+
const inputFields = slug === MEDIA ? fields.filter((f) => !MEDIA_SYSTEM_FIELDS.has(f.name)) : fields;
|
|
1070
|
+
const extraInput = slug === "users" ? { password: { type: GraphQLString } } : {};
|
|
1071
|
+
if (slug !== MEDIA) {
|
|
1072
|
+
const createInput = this.inputType(
|
|
1073
|
+
`${names.type}CreateInput`,
|
|
1074
|
+
inputFields,
|
|
1075
|
+
names.type,
|
|
1076
|
+
true,
|
|
1077
|
+
extraInput
|
|
1078
|
+
);
|
|
1079
|
+
mutation[`create${names.type}`] = {
|
|
1080
|
+
type,
|
|
1081
|
+
args: { data: { type: new GraphQLNonNull(createInput) }, ...writeArgs },
|
|
1082
|
+
resolve: async (_source, args, ctx) => {
|
|
1083
|
+
const data = status(toInput(args.data, fields), args);
|
|
1084
|
+
const doc = await ctx.cms.create(slug, data, {
|
|
1085
|
+
...access(ctx),
|
|
1086
|
+
depth: 0,
|
|
1087
|
+
...this.localeOf(args)
|
|
1088
|
+
});
|
|
1089
|
+
return written(doc, args);
|
|
1090
|
+
}
|
|
1091
|
+
};
|
|
1092
|
+
}
|
|
1093
|
+
const updateInput = this.inputType(
|
|
1094
|
+
`${names.type}UpdateInput`,
|
|
1095
|
+
inputFields,
|
|
1096
|
+
names.type,
|
|
1097
|
+
false,
|
|
1098
|
+
extraInput
|
|
1099
|
+
);
|
|
1100
|
+
mutation[`update${names.type}`] = {
|
|
1101
|
+
type,
|
|
1102
|
+
args: {
|
|
1103
|
+
id: { type: new GraphQLNonNull(GraphQLID) },
|
|
1104
|
+
data: { type: new GraphQLNonNull(updateInput) },
|
|
1105
|
+
...writeArgs
|
|
1106
|
+
},
|
|
1107
|
+
resolve: async (_source, args, ctx) => {
|
|
1108
|
+
const data = status(toInput(args.data, fields), args);
|
|
1109
|
+
const doc = await ctx.cms.update(slug, toId(args.id), data, {
|
|
1110
|
+
...access(ctx),
|
|
1111
|
+
depth: 0,
|
|
1112
|
+
...this.localeOf(args)
|
|
1113
|
+
});
|
|
1114
|
+
return written(doc, args);
|
|
1115
|
+
}
|
|
1116
|
+
};
|
|
1117
|
+
mutation[`delete${names.type}`] = {
|
|
1118
|
+
type,
|
|
1119
|
+
description: "Deletes the document and returns it. Cannot be undone.",
|
|
1120
|
+
args: { id: { type: new GraphQLNonNull(GraphQLID) } },
|
|
1121
|
+
resolve: async (_source, args, ctx) => written(await ctx.cms.delete(slug, toId(args.id), access(ctx)), {})
|
|
1122
|
+
};
|
|
1123
|
+
}
|
|
1124
|
+
globalOperations(g, type, query, mutation) {
|
|
1125
|
+
const slug = g.slug;
|
|
1126
|
+
const names = this.names.globals.get(slug);
|
|
1127
|
+
const drafts = g.drafts === true;
|
|
1128
|
+
const access = (ctx) => ({ user: ctx.user, overrideAccess: false });
|
|
1129
|
+
query[names.one] = {
|
|
1130
|
+
type,
|
|
1131
|
+
...describe(g.label),
|
|
1132
|
+
args: this.readArgs(drafts),
|
|
1133
|
+
resolve: async (_source, args, ctx) => {
|
|
1134
|
+
const read = this.readOf(args, ctx);
|
|
1135
|
+
return tag(await ctx.cms.findGlobal(slug, { ...access(ctx), depth: 0, ...read }), read);
|
|
1136
|
+
}
|
|
1137
|
+
};
|
|
1138
|
+
const input = this.inputType(`${names.type}Input`, g.fields, names.type, false, {});
|
|
1139
|
+
mutation[`update${names.type}`] = {
|
|
1140
|
+
type,
|
|
1141
|
+
args: {
|
|
1142
|
+
data: { type: new GraphQLNonNull(input) },
|
|
1143
|
+
...this.localeArgsForWrite(),
|
|
1144
|
+
...drafts ? {
|
|
1145
|
+
draft: {
|
|
1146
|
+
type: GraphQLBoolean,
|
|
1147
|
+
description: "true: save as a draft. false: publish."
|
|
1148
|
+
}
|
|
1149
|
+
} : {}
|
|
1150
|
+
},
|
|
1151
|
+
resolve: async (_source, args, ctx) => {
|
|
1152
|
+
let data = toInput(args.data, g.fields);
|
|
1153
|
+
if (drafts && typeof args.draft === "boolean")
|
|
1154
|
+
data = { ...data, status: args.draft ? "draft" : "published" };
|
|
1155
|
+
const doc = await ctx.cms.updateGlobal(slug, data, {
|
|
1156
|
+
...access(ctx),
|
|
1157
|
+
depth: 0,
|
|
1158
|
+
...this.localeOf(args)
|
|
1159
|
+
});
|
|
1160
|
+
return tag(doc, this.localeOf(args));
|
|
1161
|
+
}
|
|
1162
|
+
};
|
|
1163
|
+
}
|
|
1164
|
+
localeArgsForWrite() {
|
|
1165
|
+
return this.locale ? { locale: { type: this.locale, description: "The language the data is in." } } : {};
|
|
1166
|
+
}
|
|
1167
|
+
// ---- Input ---------------------------------------------------------------------------------
|
|
1168
|
+
inputType(name, fields, path, strict, extra) {
|
|
1169
|
+
return new GraphQLInputObjectType({
|
|
1170
|
+
name: this.claim(name),
|
|
1171
|
+
fields: () => ({ ...this.inputFields(fields, path, strict), ...extra })
|
|
1172
|
+
});
|
|
1173
|
+
}
|
|
1174
|
+
nestedInputs = /* @__PURE__ */ new Map();
|
|
1175
|
+
inputFields(fields, path, strict) {
|
|
1176
|
+
const out = {};
|
|
1177
|
+
for (const field of fields) {
|
|
1178
|
+
if (field.hidden || !isValidName(field.name)) continue;
|
|
1179
|
+
const type = this.inputOf(field, path);
|
|
1180
|
+
const required = strict && field.required === true && field.defaultValue === void 0 && !["slug", "group", "array", "blocks"].includes(field.type);
|
|
1181
|
+
out[field.name] = {
|
|
1182
|
+
type: required ? new GraphQLNonNull(type) : type,
|
|
1183
|
+
...describe(field.label)
|
|
1184
|
+
};
|
|
1185
|
+
}
|
|
1186
|
+
return out;
|
|
1187
|
+
}
|
|
1188
|
+
inputOf(field, path) {
|
|
1189
|
+
const many = (type) => hasMany(field) ? list(type) : type;
|
|
1190
|
+
switch (field.type) {
|
|
1191
|
+
case "number":
|
|
1192
|
+
return GraphQLFloat;
|
|
1193
|
+
case "boolean":
|
|
1194
|
+
return GraphQLBoolean;
|
|
1195
|
+
case "date":
|
|
1196
|
+
return DateTimeScalar;
|
|
1197
|
+
case "json":
|
|
1198
|
+
return JSONScalar;
|
|
1199
|
+
case "richText":
|
|
1200
|
+
return JSONScalar;
|
|
1201
|
+
case "select":
|
|
1202
|
+
return many(this.selectType(field, path) ?? GraphQLString);
|
|
1203
|
+
case "relationship":
|
|
1204
|
+
case "upload":
|
|
1205
|
+
return many(GraphQLID);
|
|
1206
|
+
case "blocks":
|
|
1207
|
+
return list(JSONScalar);
|
|
1208
|
+
case "group":
|
|
1209
|
+
case "array": {
|
|
1210
|
+
let type = this.nestedInputs.get(field);
|
|
1211
|
+
if (!type) {
|
|
1212
|
+
const base = `${path}${pascal(field.name)}`;
|
|
1213
|
+
const name = field.type === "group" ? `${base}Input` : `${base}RowInput`;
|
|
1214
|
+
type = new GraphQLInputObjectType({
|
|
1215
|
+
name: this.claim(name),
|
|
1216
|
+
fields: () => ({
|
|
1217
|
+
...field.type === "array" ? { id: { type: GraphQLString } } : {},
|
|
1218
|
+
...this.inputFields(field.fields, base, false)
|
|
1219
|
+
})
|
|
1220
|
+
});
|
|
1221
|
+
this.nestedInputs.set(field, type);
|
|
1222
|
+
}
|
|
1223
|
+
return field.type === "group" ? type : list(type);
|
|
1224
|
+
}
|
|
1225
|
+
default:
|
|
1226
|
+
return GraphQLString;
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
};
|
|
1230
|
+
function toWhere(input, fields, prefix = "") {
|
|
1231
|
+
const out = {};
|
|
1232
|
+
for (const [key, value] of Object.entries(input)) {
|
|
1233
|
+
if (value === void 0) continue;
|
|
1234
|
+
if (key === "AND" || key === "OR") {
|
|
1235
|
+
out[key.toLowerCase()] = value.map((w) => toWhere(w, fields));
|
|
1236
|
+
continue;
|
|
1237
|
+
}
|
|
1238
|
+
const field = fields.find((f) => f.name === key);
|
|
1239
|
+
if (field?.type === "group") {
|
|
1240
|
+
Object.assign(out, toWhere(value, field.fields, `${prefix}${key}.`));
|
|
1241
|
+
continue;
|
|
1242
|
+
}
|
|
1243
|
+
const ids = key === "id" || field?.type === "relationship" || field?.type === "upload";
|
|
1244
|
+
out[`${prefix}${key}`] = ids ? mapOperators(value, toId) : value;
|
|
1245
|
+
}
|
|
1246
|
+
return out;
|
|
1247
|
+
}
|
|
1248
|
+
function mapOperators(ops, map) {
|
|
1249
|
+
return Object.fromEntries(
|
|
1250
|
+
Object.entries(ops).map(([op, v]) => [
|
|
1251
|
+
op,
|
|
1252
|
+
op === "exists" || v === null ? v : Array.isArray(v) ? v.map(map) : map(v)
|
|
1253
|
+
])
|
|
1254
|
+
);
|
|
1255
|
+
}
|
|
1256
|
+
function toInput(data, fields) {
|
|
1257
|
+
const out = { ...data };
|
|
1258
|
+
for (const field of fields) {
|
|
1259
|
+
const value = out[field.name];
|
|
1260
|
+
if (value === void 0 || value === null) continue;
|
|
1261
|
+
switch (field.type) {
|
|
1262
|
+
case "relationship":
|
|
1263
|
+
case "upload":
|
|
1264
|
+
out[field.name] = Array.isArray(value) ? value.map(toId) : toId(value);
|
|
1265
|
+
break;
|
|
1266
|
+
case "richText":
|
|
1267
|
+
if (typeof value === "string") out[field.name] = textToDoc(value);
|
|
1268
|
+
break;
|
|
1269
|
+
case "group":
|
|
1270
|
+
out[field.name] = toInput(value, field.fields);
|
|
1271
|
+
break;
|
|
1272
|
+
case "array":
|
|
1273
|
+
out[field.name] = value.map((row) => toInput(row, field.fields));
|
|
1274
|
+
break;
|
|
1275
|
+
case "blocks":
|
|
1276
|
+
out[field.name] = value.map((row) => {
|
|
1277
|
+
const block = field.blocks.find((b) => b.slug === row?.blockType);
|
|
1278
|
+
return block && row && typeof row === "object" ? toInput(row, block.fields) : row;
|
|
1279
|
+
});
|
|
1280
|
+
break;
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
return out;
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
// src/plugin.ts
|
|
1287
|
+
function plannedSlugs(config, exclude) {
|
|
1288
|
+
const collections = /* @__PURE__ */ new Set(["users", "media"]);
|
|
1289
|
+
if (config.upload?.folders === true) collections.add("media-folders");
|
|
1290
|
+
for (const c of config.collections ?? []) collections.add(c.slug);
|
|
1291
|
+
const keep = (slug) => !INTERNAL_COLLECTIONS2.has(slug) && slug !== API_KEYS2 && !exclude.includes(slug);
|
|
1292
|
+
return {
|
|
1293
|
+
collections: [...collections].filter(keep),
|
|
1294
|
+
globals: (config.globals ?? []).map((g) => g.slug).filter((s) => !exclude.includes(s))
|
|
1295
|
+
};
|
|
1296
|
+
}
|
|
1297
|
+
function graphqlPlugin(options = {}) {
|
|
1298
|
+
return definePlugin((config) => {
|
|
1299
|
+
const planned = plannedSlugs(config, options.exclude ?? []);
|
|
1300
|
+
checkNames(planned.collections, planned.globals, options.names);
|
|
1301
|
+
const schemas = /* @__PURE__ */ new WeakMap();
|
|
1302
|
+
const schemaOf = (cms) => {
|
|
1303
|
+
let schema = schemas.get(cms.config);
|
|
1304
|
+
if (!schema) {
|
|
1305
|
+
schema = buildGraphQLSchema(cms.config, options);
|
|
1306
|
+
schemas.set(cms.config, schema);
|
|
1307
|
+
}
|
|
1308
|
+
return schema;
|
|
1309
|
+
};
|
|
1310
|
+
const handler = (args) => handleGraphQL(args, {
|
|
1311
|
+
schema: schemaOf(args.cms),
|
|
1312
|
+
depth: options.limits?.depth ?? DEFAULT_DEPTH,
|
|
1313
|
+
documents: options.limits?.documents ?? DEFAULT_DOCUMENTS,
|
|
1314
|
+
introspection: options.introspection ?? true,
|
|
1315
|
+
graphiql: options.graphiql ?? process.env.NODE_ENV !== "production"
|
|
1316
|
+
});
|
|
1317
|
+
const path = options.path ?? "/graphql";
|
|
1318
|
+
const generate = {
|
|
1319
|
+
name: "generate:graphql",
|
|
1320
|
+
description: "Write the GraphQL schema (SDL) to a file, for codegen",
|
|
1321
|
+
help: `Usage: easy-cms generate:graphql [file] [options]
|
|
1322
|
+
|
|
1323
|
+
Writes the schema of the GraphQL API (graphqlPlugin) as SDL, for GraphQL Code Generator and
|
|
1324
|
+
other tools. Default file: schema.graphql. Opens the database like the other commands.
|
|
1325
|
+
`,
|
|
1326
|
+
run: async ({ cms, args, log }) => {
|
|
1327
|
+
const out = args[0] ?? "schema.graphql";
|
|
1328
|
+
const file = isAbsolute(out) ? out : resolve(cms.cwd, out);
|
|
1329
|
+
await writeFile(file, `${printSchema(schemaOf(cms))}
|
|
1330
|
+
`);
|
|
1331
|
+
log(`Wrote ${file}`);
|
|
1332
|
+
return 0;
|
|
1333
|
+
}
|
|
1334
|
+
};
|
|
1335
|
+
return {
|
|
1336
|
+
...config,
|
|
1337
|
+
endpoints: [
|
|
1338
|
+
...config.endpoints ?? [],
|
|
1339
|
+
{ path, method: "get", handler },
|
|
1340
|
+
{ path, method: "post", handler }
|
|
1341
|
+
],
|
|
1342
|
+
commands: [...config.commands ?? [], generate]
|
|
1343
|
+
};
|
|
1344
|
+
}, INFO);
|
|
1345
|
+
}
|
|
1346
|
+
export {
|
|
1347
|
+
DateTimeScalar,
|
|
1348
|
+
JSONScalar,
|
|
1349
|
+
buildGraphQLSchema,
|
|
1350
|
+
createContext,
|
|
1351
|
+
graphqlPlugin,
|
|
1352
|
+
runGraphQL
|
|
1353
|
+
};
|