-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
46 lines (41 loc) · 1.21 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
const {
DirectiveLocation,
GraphQLDirective,
defaultFieldResolver,
} = require('graphql');
const { SchemaDirectiveVisitor } = require('graphql-tools');
const { plural, singular } = require('pluralize');
const createDirective = ({ name, description, formatter }) =>
class PluralizeDirective extends SchemaDirectiveVisitor {
static getDirectiveDeclaration(directiveName = name, schema) {
return new GraphQLDirective({
name: directiveName,
description,
locations: [DirectiveLocation.FIELD_DEFINITION],
});
}
visitFieldDefinition(field) {
const { resolve = defaultFieldResolver } = field;
// eslint-disable-next-line
field.resolve = function(...args) {
return Promise.resolve(resolve.apply(this, args)).then(result => {
if (typeof result === 'string') {
return formatter(result);
}
return result;
});
};
}
};
module.exports = {
plural: createDirective({
name: 'plural',
description: 'Pluralizes a field (string)',
formatter: plural,
}),
singular: createDirective({
name: 'singular',
description: 'Singularizes a field (string)',
formatter: singular,
}),
};