forked from prismake/typegql
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
76 lines (65 loc) · 1.62 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
import express from 'express'
import { GraphQLResolveInfo } from 'graphql'
import getFieldNames from 'graphql-list-fields'
import {
SchemaRoot,
Query,
ObjectType,
Field,
Inject,
compileSchema
} from 'decapi'
import 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 {
@Field()
foo: string
@Field()
bar: string
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'
}
}
}
@SchemaRoot()
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)