Repository navigation
Expand file tree
/
Copy pathindex.ts
More file actions
74 lines (64 loc) · 1.65 KB
/
Copy pathindex.ts
File metadata and controls
74 lines (64 loc) · 1.65 KB
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
import * as express from 'express';
import { GraphQLResolveInfo } from 'graphql';
import * as getFieldNames from 'graphql-list-fields';
import {
Schema,
Query,
ObjectType,
Field,
Inject,
compileSchema,
} from 'typegql';
import * as graphqlHTTP from 'express-graphql';
function NeededFields(filter: string[] = []) {
return Inject(({ info }) => {
const selectionFieldNames: string[] = getFieldNames(info); // let's get all needed fields
// if there is no filter, return all selected field names
if (!filter || !filter.length) {
return selectionFieldNames;
}
// let's return only those allowed
return selectionFieldNames.filter(fieldName => {
return filter.includes(fieldName);
});
});
}
// let's create some object that is aware of fields that it needs to know about
@ObjectType()
class LazyObject {
constructor(neededFields: string[]) {
console.log(
'I will only perform expensive operations for fields:',
neededFields,
);
if (neededFields.includes['foo']) {
this.foo = 'I have foo';
}
if (neededFields.includes['bar']) {
this.bar = 'I have bar';
}
}
@Field() foo: string;
@Field() bar: string;
}
@Schema()
class SuperSchema {
@Query()
foo(
@NeededFields(['foo', 'bar'])
neededFields: string[], // this arg will tell if `foo` and `bar` are needed
): LazyObject {
console.log('Needed fields are: ', { neededFields });
return new LazyObject(neededFields);
}
}
const compiledSchema = compileSchema(SuperSchema);
const app = express();
app.use(
'/graphql',
graphqlHTTP({
schema: compiledSchema,
graphiql: true,
}),
);
app.listen(3000);