-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
56 lines (47 loc) · 1.24 KB
/
index.js
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
const {
GraphQLID,
GraphQLList,
GraphQLString,
GraphQLInt,
DirectiveLocation,
GraphQLDirective,
} = require('graphql');
const { SchemaDirectiveVisitor } = require('graphql-tools');
const { createHash } = require('crypto');
class UniqueIdDirective extends SchemaDirectiveVisitor {
static getDirectiveDeclaration(directiveName = 'uid') {
return new GraphQLDirective({
name: directiveName,
description: 'Generates unique ID based on specifics fields',
locations: [DirectiveLocation.OBJECT],
args: {
from: {
type: new GraphQLList(GraphQLString, GraphQLInt),
},
},
});
}
visitObject(type) {
const { name = 'uid', from } = this.args;
const fields = type.getFields();
if (name in fields) {
throw new Error(`Conflicting field name ${name}`);
}
fields[name] = {
name,
type: GraphQLID,
description: 'Unique ID',
args: [],
isDeprecated: false,
resolve(object) {
const hash = createHash('sha1');
hash.update(type.name);
from.forEach(fieldName => {
hash.update(String(object[fieldName]));
});
return hash.digest('hex');
},
};
}
}
module.exports = UniqueIdDirective;