graphql-jerky 1.0.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/LICENCE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022-2023 Steve Lam
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,252 @@
1
+ # Jerky
2
+
3
+ Jerky is a schema-first static graphql schema lightweight code generator.
4
+
5
+ The benefit of such a tool is to remove the requirement of parsing the graphql
6
+ schema at runtime while still employing a schema-first development experience.
7
+ This is useful for reducing startup or cold start times which is important for
8
+ environments where potentially many short-lived instances are spawned in quick
9
+ succession such as on serverless platforms.
10
+
11
+ In addition to runtime benefits, scalar, resolve, and subscribe functions are
12
+ automatically linked in the schema, and typescript Types are automatically
13
+ generated based on the schema definition.
14
+
15
+ Jerky is made to interoperate with the reference `graphql-js` library and is not
16
+ a standalone GraphQL implementation.
17
+
18
+ ## Usage
19
+
20
+ ```
21
+ npx graphql-jerky
22
+ ```
23
+
24
+ OR
25
+
26
+ ```
27
+ deno run -A src/command/jerky.ts
28
+ ```
29
+
30
+ By default, the working directory is searched recursively for `*.graphql` files.
31
+ All of which are combined into a single schema and rendered to `schema_gen.ts`
32
+ in the same directory.
33
+
34
+ A path to a directory or file can be passed as the first parameter to limit to
35
+ scope of the search.
36
+
37
+ ### Options
38
+
39
+ #### --graphql
40
+
41
+ The `--graphql` option specifies the module from which the graphql types will be
42
+ imported. Defaults to `graphql`.
43
+
44
+ This is sometimes necessary depending on your target platform or runtime. In
45
+ particular, a node project would probably `graphql` from npm, where as a deno
46
+ project may use `npm:graphql` instead.
47
+
48
+ #### --scalars
49
+
50
+ The `--scalars` option specifies the module from which scalar functions are
51
+ imported.
52
+
53
+ This is used to specify the `serialize`, `parseValue`, and `parseLiteral`
54
+ functions that are configure `GraphQLScalarType`s.
55
+
56
+ For example, if a custom scalar is defined like this:
57
+
58
+ ```gql
59
+ scalar Date
60
+ ```
61
+
62
+ The corresponding scalars file could look like this:
63
+
64
+ ```ts
65
+ export const Date = {
66
+ serialize(value: Date): string {
67
+ return value.toISOString();
68
+ },
69
+ parseValue(value: unknown): Date {
70
+ if (typeof value !== "string") {
71
+ throw new Error("Date must be a string");
72
+ }
73
+
74
+ return new globalThis.Date(value);
75
+ },
76
+ };
77
+ ```
78
+
79
+ #### --resolvers
80
+
81
+ The `--resolvers` option specifies a directory of modules from which resolver
82
+ functions are imported.
83
+
84
+ Object and interface types defined in the schema are correlated to a file in the
85
+ specified directory by name. Within each file, fields of the corresponding type
86
+ are also correlated to the exports by name.
87
+
88
+ Each export must be a function in the form of
89
+ [`GraphQLFieldResolver`](https://github.com/graphql/graphql-js/blob/e9a81f2ba9020ec5fd0f67f5553ccabe392e95e8/src/type/definition.ts#L879).
90
+
91
+ For example, if a schema is defined like this:
92
+
93
+ ```gql
94
+ type Query {
95
+ show(id: ID!): Show
96
+ }
97
+
98
+ type Show {
99
+ name: String!
100
+ }
101
+ ```
102
+
103
+ The corresponding resolvers directory could look like this:
104
+
105
+ ```ts
106
+ // path/to/resolvers/Query.ts
107
+
108
+ import { Query } from "path/to/schema_gen.ts";
109
+ import { data, Show } from "path/to/data.ts";
110
+
111
+ export function show(source: null, { id }: Query.ShowArgs): Show {
112
+ return data.shows[id];
113
+ }
114
+ ```
115
+
116
+ ```ts
117
+ // path/to/resolvers/Show.ts
118
+
119
+ import { Show } from "path/to/data.ts";
120
+
121
+ export function name(source: Show): string {
122
+ return source.show_name;
123
+ }
124
+ ```
125
+
126
+ Alternatively to a single file containing all field resolvers, for large types
127
+ like `Query` or `Mutation`, it may be preferrable to break split of field
128
+ resolvers into separate files within a subdirectory of the same name as the
129
+ corresponding type for better organization.
130
+
131
+ For example, if a schema is defined like this:
132
+
133
+ ```gql
134
+ type Query {
135
+ show(id: ID!): Show
136
+ actor(id: ID!): Actor
137
+ }
138
+ ```
139
+
140
+ The `Query` resolvers may be split up into files like this:
141
+
142
+ ```ts
143
+ // path/to/resolvers/Query/shows.ts
144
+
145
+ import { Query } from "path/to/schema_gen.ts";
146
+ import { data, Show } from "path/to/data.ts";
147
+
148
+ export function show(source: null, { id }: Query.ShowArgs): Show {
149
+ return data.shows[id];
150
+ }
151
+ ```
152
+
153
+ ```ts
154
+ // path/to/resolvers/Query/actors.ts
155
+
156
+ import { Query } from "path/to/schema_gen.ts";
157
+ import { Actor, data } from "path/to/data.ts";
158
+
159
+ export function actors(source: null, { id }: Query.ActorArgs): Actor {
160
+ return data.actors[id];
161
+ }
162
+ ```
163
+
164
+ #### --subscribers
165
+
166
+ The `--subscribers` option specifies the module from which subscribe functions
167
+ are imported. This works in the same way as any particular type from the
168
+ `--resolvers` option, except it is for the `Subscription` type only.
169
+
170
+ #### --field-directives
171
+
172
+ The `--field-directives` option specifies the module from which field directive
173
+ functions are imported.
174
+
175
+ Field directive functions work like middleware for field resolvers. They receive
176
+ a field resolver function and return a field resolver function. The function
177
+ that is returned may be a completely new function, or same function that was
178
+ passed in as the parameter. They are invoked once on start, and never again.
179
+
180
+ For example, a field directive that ensures that only authorized users may
181
+ access a field may look like this:
182
+
183
+ ```graphql
184
+ directive @secure(level: Int!) on FIELD_DEFINITION
185
+
186
+ type Mutation {
187
+ secrets(): String @secure(level: 9001)
188
+ }
189
+ ```
190
+
191
+ ```js
192
+ export function secure(next: GraphQLFieldResolver<any, any>, { level }: SecureDirectiveArgs): GraphQLFieldResolver<any, any> {
193
+ return (src: any, args: any, ctx: any, info: GraphQLResolveInfo) => {
194
+ if (!ctx.authorization) {
195
+ throw new GraphQLError("unauthorized");
196
+ }
197
+
198
+ if (level > ctx.authorization.level) {
199
+ throw new GraphQLError(`authorization level ${level} is required`);
200
+ }
201
+
202
+ // src, args, ctx can be mutated here before being passed to the next resolver
203
+
204
+ return next(src, args, ctx, info);
205
+ }
206
+ }
207
+ ```
208
+
209
+ #### --input-directives
210
+
211
+ The `--input-directives` option specifies the module from which input and
212
+ argument directive functions are imported.
213
+
214
+ Input and argument directive functions work like transforms. They receive a
215
+ value, do some processing with it, and return a value to be used in place of the
216
+ original value. They are invoked every time such a value is received.
217
+
218
+ For example, an input directive that requires a value to be an email address may
219
+ look like this:
220
+
221
+ ```graphql
222
+ directive @email on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION
223
+
224
+ type Mutation {
225
+ sendMessage(to: String! @email): String
226
+ }
227
+ ```
228
+
229
+ ```js
230
+ export function email(s: string, {}: EmailDirectiveArgs): string {
231
+ if (!s.includes("@")) {
232
+ throw new Error("must be a valid email");
233
+ }
234
+
235
+ return s;
236
+ }
237
+ ```
238
+
239
+ ## Goals
240
+
241
+ - Generate runtime-agnostic code
242
+ - Interoperate with `graphql-js`
243
+ - Be easily configurable for any target environment
244
+ - Keep the `graphql-js` version of Jerky independent of that of the target
245
+ environment
246
+ - Expose APIs for custom integrations
247
+
248
+ ## Non-Goals
249
+
250
+ - Teaching GraphQL concepts or ideas
251
+ - Extending GraphQL with custom features
252
+ - Overthrowing the Galactic Federation
@@ -0,0 +1,69 @@
1
+ #!/usr/bin/env node
2
+
3
+ 'use strict';
4
+
5
+ var commander = require('commander');
6
+ var fs = require('fs/promises');
7
+ var path = require('path');
8
+ var lib = require('../lib.cjs');
9
+
10
+ commander.program
11
+ .name("jerky")
12
+ .version("0.1.0")
13
+ .description("Schema-first GraphQL typescript code generator")
14
+ .argument("[schema]", "Path to schema file or directory.")
15
+ .option("-o, --out <destination>", "Path to write schema_gen.ts.")
16
+ .option("--graphql <module>", "graphql module import specifier.")
17
+ .option("--scalars <module>", "scalars module import specifier.")
18
+ .option("--resolvers <directory>", "resolvers directory path.")
19
+ .option("--subscribers <module>", "subscriber module import specifier.")
20
+ .option("--field-directives <module>", "field directives module import specifier.")
21
+ .option("--input-directives <module>", "input directives module import specifier.")
22
+ .option("--ext <mode>", "whether \"keep\", \"replace\", or \"omit\" the .ts extension in import statements.")
23
+ .showHelpAfterError(true);
24
+ commander.program.parse();
25
+ const { out = "schema_gen.ts", graphql = "graphql", scalars, resolvers, subscribers, fieldDirectives, inputDirectives, ext = "omit", } = commander.program.opts();
26
+ const [schema = "."] = commander.program.args;
27
+ (async () => {
28
+ let outfile = out;
29
+ if (!outfile.pathname.endsWith("/")) {
30
+ // test if it's a directory
31
+ try {
32
+ const stat = await fs.stat(outfile);
33
+ if (stat.isDirectory()) {
34
+ outfile += "/";
35
+ }
36
+ }
37
+ catch {
38
+ // probably doesn't exist yet
39
+ }
40
+ }
41
+ if (outfile.endsWith("/")) {
42
+ outfile += "schema_gen.ts";
43
+ }
44
+ if (!outfile.endsWith(".ts")) {
45
+ outfile += ".ts";
46
+ }
47
+ switch (ext) {
48
+ default:
49
+ throw new Error(`invalid mode for --ext: ${ext}`);
50
+ case "keep":
51
+ case "replace":
52
+ case "omit":
53
+ }
54
+ await fs.writeFile(outfile, lib.generate(await lib.parseSchema(path.resolve(schema)), outfile.pathname, {
55
+ scalarsInfo: scalars ? await lib.parseScalars(scalars) : undefined,
56
+ fieldDirectivesInfo: fieldDirectives ? await lib.parseTypeResolvers("", fieldDirectives) : undefined,
57
+ inputDirectivesInfo: inputDirectives ? await lib.parseTypeResolvers("", inputDirectives) : undefined,
58
+ resolversInfo: resolvers ? await lib.parseResolvers(resolvers) : undefined,
59
+ subscribersInfo: subscribers ? await lib.parseTypeResolvers("Subscription", subscribers) : undefined,
60
+ graphqlModuleSpecifier: graphql,
61
+ extMode: ext,
62
+ }));
63
+ })().catch((err) => {
64
+ console.error(err.message);
65
+ console.log();
66
+ if (process.argv.length === 2 || (process.argv.length === 3 && process.argv[2] === "help")) {
67
+ commander.program.outputHelp();
68
+ }
69
+ });
@@ -0,0 +1,76 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { program } from 'commander';
4
+ import fs from 'fs/promises';
5
+ import path from 'path';
6
+ import { generate, parseScalars as parse, parseTypeResolvers, parseResolvers as parse$1, parseSchema as parse$2 } from '../lib.mjs';
7
+ import 'graphql';
8
+ import 'jennifer-js';
9
+ import 'jennifer-js/format';
10
+ import 'just-partition';
11
+ import 'just-pascal-case';
12
+ import 'url';
13
+ import 'typescript';
14
+ import 'glob';
15
+ import 'just-zip-it';
16
+
17
+ program
18
+ .name("jerky")
19
+ .version("0.1.0")
20
+ .description("Schema-first GraphQL typescript code generator")
21
+ .argument("[schema]", "Path to schema file or directory.")
22
+ .option("-o, --out <destination>", "Path to write schema_gen.ts.")
23
+ .option("--graphql <module>", "graphql module import specifier.")
24
+ .option("--scalars <module>", "scalars module import specifier.")
25
+ .option("--resolvers <directory>", "resolvers directory path.")
26
+ .option("--subscribers <module>", "subscriber module import specifier.")
27
+ .option("--field-directives <module>", "field directives module import specifier.")
28
+ .option("--input-directives <module>", "input directives module import specifier.")
29
+ .option("--ext <mode>", "whether \"keep\", \"replace\", or \"omit\" the .ts extension in import statements.")
30
+ .showHelpAfterError(true);
31
+ program.parse();
32
+ const { out = "schema_gen.ts", graphql = "graphql", scalars, resolvers, subscribers, fieldDirectives, inputDirectives, ext = "omit", } = program.opts();
33
+ const [schema = "."] = program.args;
34
+ (async () => {
35
+ let outfile = out;
36
+ if (!outfile.pathname.endsWith("/")) {
37
+ // test if it's a directory
38
+ try {
39
+ const stat = await fs.stat(outfile);
40
+ if (stat.isDirectory()) {
41
+ outfile += "/";
42
+ }
43
+ }
44
+ catch {
45
+ // probably doesn't exist yet
46
+ }
47
+ }
48
+ if (outfile.endsWith("/")) {
49
+ outfile += "schema_gen.ts";
50
+ }
51
+ if (!outfile.endsWith(".ts")) {
52
+ outfile += ".ts";
53
+ }
54
+ switch (ext) {
55
+ default:
56
+ throw new Error(`invalid mode for --ext: ${ext}`);
57
+ case "keep":
58
+ case "replace":
59
+ case "omit":
60
+ }
61
+ await fs.writeFile(outfile, generate(await parse$2(path.resolve(schema)), outfile.pathname, {
62
+ scalarsInfo: scalars ? await parse(scalars) : undefined,
63
+ fieldDirectivesInfo: fieldDirectives ? await parseTypeResolvers("", fieldDirectives) : undefined,
64
+ inputDirectivesInfo: inputDirectives ? await parseTypeResolvers("", inputDirectives) : undefined,
65
+ resolversInfo: resolvers ? await parse$1(resolvers) : undefined,
66
+ subscribersInfo: subscribers ? await parseTypeResolvers("Subscription", subscribers) : undefined,
67
+ graphqlModuleSpecifier: graphql,
68
+ extMode: ext,
69
+ }));
70
+ })().catch((err) => {
71
+ console.error(err.message);
72
+ console.log();
73
+ if (process.argv.length === 2 || (process.argv.length === 3 && process.argv[2] === "help")) {
74
+ program.outputHelp();
75
+ }
76
+ });