-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
426 lines (394 loc) · 11.4 KB
/
index.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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
import {
GraphQLBoolean,
GraphQLFieldConfig,
GraphQLFieldConfigArgumentMap,
GraphQLFieldConfigMap,
GraphQLFieldResolver,
GraphQLFloat,
GraphQLInputFieldConfig,
GraphQLInputFieldConfigMap,
GraphQLInputObjectType,
GraphQLInterfaceType,
GraphQLIsTypeOfFn,
GraphQLList,
GraphQLNonNull,
GraphQLObjectType,
GraphQLResolveInfo,
GraphQLScalarType,
GraphQLString,
Thunk,
} from "graphql";
import "reflect-metadata";
const getParameterNames = require("get-parameter-names");
type Maybe<T> = T | null | undefined;
///////////////////////////////////////////////////////////////////////////////
//
// Keep track data collected when decorators are evaluated
//
const objectsBuilt = new WeakMap<Object, GraphQLObjectType>();
const objectFields = new WeakMap<
Object,
{ [name: string]: { conf: Thunk<FieldConfig>; typeWrap?: (t: any) => any } }
>();
const objectFieldParams = new WeakMap<
Object,
Map<string, Map<number, ParamConfigWrap>>
>();
const inputObjectsBuilt = new WeakMap<Object, GraphQLInputObjectType>();
const inputFields = new WeakMap<
Object,
{
[name: string]: {
conf: Thunk<InputFieldConfig>;
typeWrap?: (t: any) => any;
};
}
>();
/**
* Return the GraphQLObjectType version of a given class
*/
export function asGQLObject(t: any): GraphQLObjectType {
const obj = objectsBuilt.get(t);
if (!obj) {
throw new TypeError(`Unable to asGQLObject. Not found in objectsBuilt`);
}
return obj;
}
/**
* Guess the GraphQL type of a value emmited by TypeScript compiler using `reflect-metadata`
*/
function metaDataTypeToGQLType(
t: any
): GraphQLScalarType | GraphQLObjectType | InputObjectTypeConfig | null {
switch (t) {
case String:
return GraphQLString;
case Number:
return GraphQLFloat;
case Boolean:
return GraphQLBoolean;
}
const obj = objectsBuilt.get(t) || inputObjectsBuilt.get(t);
if (obj) {
return obj;
}
// Cannot guess the type... I wish TS emitted more detailed metadata.
return null;
}
function asGQL(t: any): any {
return metaDataTypeToGQLType(t) || t;
}
///////////////////////////////////////////////////////////////////////////////
//
// Decorators
//
export interface ObjectTypeConfig {
name?: string;
description?: Maybe<string>;
interfaces?: Thunk<Maybe<GraphQLInterfaceType[]>>;
fields?: Thunk<GraphQLFieldConfigMap<any, any>>;
isTypeOf?: Maybe<GraphQLIsTypeOfFn<any, any>>;
}
export function ObjectType(conf: ObjectTypeConfig = {}): ClassDecorator {
return function (daClass) {
const target = daClass.prototype;
objectsBuilt.set(
daClass,
new GraphQLObjectType(
Object.assign(
{},
{
name: daClass.name,
fields(): GraphQLFieldConfigMap<any, any> {
const fields: GraphQLFieldConfigMap<any, any> = {};
const fieldsConfs = objectFields.get(target) || {};
for (const name in fieldsConfs) {
if (fieldsConfs.hasOwnProperty(name)) {
let { conf, typeWrap } = fieldsConfs[name];
if (typeof conf === "function") {
conf = conf();
}
fields[name] = buildField(target, name, conf, typeWrap);
}
}
return fields;
},
},
conf
)
)
);
};
}
export interface FieldConfig {
type?: any;
deprecationReason?: Maybe<string>;
description?: Maybe<string>;
args?: GraphQLFieldConfigArgumentMap;
resolve?: GraphQLFieldResolver<any, any, any>;
subscribe?: GraphQLFieldResolver<any, any, any>;
}
export function Field(
conf: Thunk<FieldConfig> = {},
typeWrap?: (t: any) => any
): PropertyDecorator {
return function (target, propertyKey) {
if (typeof propertyKey !== "string") {
throw new TypeError("Symbols are not supported");
}
const map: any = objectFields.get(target) || {};
map[propertyKey] = { conf, typeWrap };
objectFields.set(target, map);
};
}
function buildField(
target: Object,
propertyKey: string,
conf: FieldConfig,
typeWrap?: (t: any) => any
): GraphQLFieldConfig<any, any> {
const args: GraphQLFieldConfigArgumentMap = {};
let guessType;
let resolve: GraphQLFieldResolver<any, any, any> | undefined;
const type = Reflect.getMetadata("design:type", target, propertyKey);
if (type === Function) {
const ptypes: any[] =
Reflect.getMetadata("design:paramtypes", target, propertyKey) || [];
const rtype = Reflect.getMetadata("design:returntype", target, propertyKey);
const daMethod: Function = (target as any)[propertyKey];
const pnames = getParameterNames(daMethod);
let paramConfigs: Map<number, ParamConfigWrap> | undefined;
const objFieldParams = objectFieldParams.get(target);
if (objFieldParams) {
paramConfigs = objFieldParams.get(propertyKey) || new Map();
}
const argOrder: ("context" | "info" | { name: string })[] = [];
for (let i = 0; i < Math.max(pnames.length, ptypes.length); i++) {
const pname = pnames[i];
const ptype = ptypes[i];
const param = (paramConfigs && paramConfigs.get(i)) || { conf: {} };
if (param === "context" || param === "info") {
argOrder.push(param);
continue;
}
const pconf =
typeof param.conf === "function" ? param.conf() : param.conf;
const name = (pconf.name = pconf.name || pname);
argOrder.push({ name });
args[name] = Object.assign(
{},
{ type: metaDataTypeToGQLType(ptype) },
pconf
);
if (!args[name].type) {
throw new TypeError(
`${target.constructor.name}.${propertyKey}[${i}] - Cannot guess the parameter type, specify it with @Param({type: ..}) `
);
}
args[name].type = asGQL(args[name].type);
if (param.typeWrap) {
args[name].type = param.typeWrap(args[name].type);
}
}
guessType = metaDataTypeToGQLType(rtype);
resolve = function (
source: any,
args: any,
context: any,
info: GraphQLResolveInfo
) {
const argsOrder = [];
for (const arg of argOrder) {
switch (arg) {
case "context":
argsOrder.push(context);
break;
case "info":
argsOrder.push(info);
break;
default:
if (arg.name) {
argsOrder.push(args[arg.name]);
}
}
}
return daMethod.apply(source, argsOrder);
};
} else {
guessType = metaDataTypeToGQLType(type);
}
const qlFieldConfig = Object.assign(
{},
{
type: guessType,
args,
resolve,
},
conf
);
if (!qlFieldConfig.type) {
throw new TypeError(
`${target.constructor.name}.${propertyKey} - Cannot guess the GQL output type, specify it with @Field({type: ..}) `
);
}
qlFieldConfig.type = asGQL(qlFieldConfig.type);
if (typeWrap) {
qlFieldConfig.type = typeWrap(qlFieldConfig.type);
}
return qlFieldConfig;
}
export interface ParamConfig {
name?: string;
type?: any;
defaultValue?: any;
description?: Maybe<string>;
}
type ParamConfigWrap =
| "context"
| "info"
| {
conf: Thunk<ParamConfig>;
typeWrap?: (t: any) => any;
};
function makeParamDecorator(conf: ParamConfigWrap): ParameterDecorator {
return function (target, propertyKey, parameterIndex) {
if (typeof propertyKey !== "string") {
throw new TypeError("Symbols are not supported");
}
const fieldMap: Map<string, Map<number, any>> =
objectFieldParams.get(target) || new Map();
const paramMap: Map<number, ParamConfigWrap> =
fieldMap.get(propertyKey) || new Map();
paramMap.set(parameterIndex, conf);
fieldMap.set(propertyKey, paramMap);
objectFieldParams.set(target, fieldMap);
};
}
export function Param(
conf: Thunk<ParamConfig> = {},
typeWrap?: (t: any) => any
): ParameterDecorator {
return makeParamDecorator({ conf, typeWrap });
}
export function ParamCtx(): ParameterDecorator {
return makeParamDecorator("context");
}
export function ParamInfo(): ParameterDecorator {
return makeParamDecorator("info");
}
export interface InputObjectTypeConfig {
name?: string;
description?: Maybe<string>;
fields?: Thunk<GraphQLInputFieldConfigMap>;
}
export function InputObjectType(
conf: InputObjectTypeConfig = {}
): ClassDecorator {
return function (daClass) {
const target = daClass.prototype;
inputObjectsBuilt.set(
daClass,
new GraphQLInputObjectType(
Object.assign(
{},
{
name: daClass.name,
fields() {
const fields: GraphQLInputFieldConfigMap = {};
const fieldsConfs = inputFields.get(target) || {};
for (const name in fieldsConfs) {
if (fieldsConfs.hasOwnProperty(name)) {
let { conf, typeWrap } = fieldsConfs[name];
if (typeof conf === "function") {
conf = conf();
}
fields[name] = buildInputField(target, name, conf, typeWrap);
}
}
return fields;
},
},
conf
)
)
);
};
}
export interface InputFieldConfig {
type?: any;
defaultValue?: any;
description?: Maybe<string>;
}
export function InputField(
conf: Thunk<InputFieldConfig> = {},
typeWrap?: (t: any) => any
): PropertyDecorator {
return function (target, propertyKey) {
if (typeof propertyKey !== "string") {
throw new TypeError("Symbols are not supported");
}
const map = inputFields.get(target) || {};
map[propertyKey] = { conf, typeWrap };
inputFields.set(target, map);
};
}
function buildInputField(
target: Object,
propertyKey: string,
conf: InputFieldConfig,
typeWrap?: (t: any) => any
): GraphQLInputFieldConfig {
const type = Reflect.getMetadata("design:type", target, propertyKey);
const guessType = metaDataTypeToGQLType(type);
const qlFieldConfig = Object.assign({}, { type: guessType }, conf);
if (!qlFieldConfig.type) {
throw new TypeError(
`${target.constructor.name}.${propertyKey} - Cannot guess the GQL input type, specify it with @InputField({type: ..}) `
);
}
qlFieldConfig.type = asGQL(qlFieldConfig.type);
if (typeWrap) {
qlFieldConfig.type = typeWrap(qlFieldConfig.type);
}
return qlFieldConfig;
}
///////////////////////////////////////////////////////////////////////////////
//
// Convenience for not-null (i.e. _B_ang!) and _L_ists
//
function wrapB(t: any) {
return new GraphQLNonNull(t);
}
function wrapL(t: any) {
return new GraphQLList(new GraphQLNonNull(t));
}
function wrapLB(t: any) {
return wrapB(wrapL(t));
}
export function ParamB(conf?: Thunk<ParamConfig>) {
return Param(conf, wrapB);
}
export function ParamL(conf?: Thunk<ParamConfig>) {
return Param(conf, wrapL);
}
export function ParamLB(conf?: Thunk<ParamConfig>) {
return Param(conf, wrapLB);
}
export function FieldB(conf?: Thunk<FieldConfig>) {
return Field(conf, wrapB);
}
export function FieldL(conf?: Thunk<FieldConfig>) {
return Field(conf, wrapL);
}
export function FieldLB(conf?: Thunk<FieldConfig>) {
return Field(conf, wrapLB);
}
export function InputFieldB(conf?: Thunk<InputFieldConfig>) {
return InputField(conf, wrapB);
}
export function InputFieldL(conf?: Thunk<InputFieldConfig>) {
return InputField(conf, wrapL);
}
export function InputFieldLB(conf?: Thunk<InputFieldConfig>) {
return InputField(conf, wrapLB);
}