UNPKG

1.78 kBPlain TextView Raw
1import { GraphQLScalarType, Kind, GraphQLError } from 'graphql';
2
3export type RootResolver<T, Context> = {
4 [P in keyof T]: T[P] extends (args: infer Args) => infer R ? (args: Args, ctx: Context) => Return<R> : never
5};
6
7export type QueryParameters<Q> = { [P in keyof Q]: Q[P] extends (args: infer Args) => unknown ? Args : never };
8
9// type PromisifyObj<T> = { [P in keyof T]: PromisifyValue<T[P]> };
10// type Obj<T> = PromisifyObj<T> | Promise<PromisifyObj<T>> | (() => PromisifyObj<T>) | (() => Promise<PromisifyObj<T>>);
11// type PromisifyPrimitive<T> = T | Promise<T> | (() => T) | (() => Promise<T>);
12// type PromisifyValue<T> = [T] extends [object]
13// ? (T extends Date ? PromisifyPrimitive<Date> : Obj<T>)
14// : PromisifyPrimitive<T>;
15
16// export type Return<T> = Promise<[T] extends [object] ? ([T] extends [Date] ? Date : PromisifyObj<T>) : T>;
17export type Return<T> = Promise<T>;
18
19export function fromPromise<T>(val: Promise<T> | (() => Promise<T>) | T) {
20 return (val as unknown) as T extends Array<Promise<infer V>> ? V[] : T extends Array<() => Promise<infer V>> ? V : T;
21}
22
23const customTypeMap = new Map<string, GraphQLScalarType>();
24
25export const graphQLBigintTypeFactory = (typeName: string) => {
26 if (!/ID$/.test(typeName)) return;
27 if (customTypeMap.has(typeName)) return customTypeMap.get(typeName);
28 const type = new GraphQLScalarType({
29 name: typeName,
30 serialize: value,
31 parseValue: value,
32 parseLiteral(ast) {
33 if (ast.kind === Kind.STRING) {
34 return value(ast.value);
35 }
36 return null;
37 },
38 });
39 customTypeMap.set(typeName, type);
40 return type;
41
42 function value(value: string) {
43 try {
44 if (BigInt(value) === 0n) throw 1;
45 } catch (e) {
46 throw new GraphQLError(`${typeName} should be numeric string: ${value}`);
47 }
48 return value;
49 }
50};