Skip to content

Commit 6c4e31e

Browse files
committed
add type converter until
joiToStringScalaType
1 parent ac815d0 commit 6c4e31e

File tree

2 files changed

+103
-0
lines changed

2 files changed

+103
-0
lines changed
Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,71 @@
1+
import { expect } from 'chai';
2+
import _ from 'lodash';
3+
import {
4+
graphql,
5+
GraphQLString,
6+
GraphQLScalarType,
7+
GraphQLObjectType,
8+
GraphQLSchema,
9+
} from 'graphql';
10+
import Joi from 'joi';
11+
import {
12+
joiToStringScalaType,
13+
} from '../typeConverter';
14+
15+
describe('typeConverter', () => {
16+
describe('joiToStringScalaType', () => {
17+
it('can convert Joi String type to GraphQLScalarType ', async () => {
18+
const schema = Joi.string().email();
19+
20+
const result = joiToStringScalaType('email', schema);
21+
const expectResult = new GraphQLScalarType({
22+
name: 'email',
23+
serialize: () => {},
24+
parseValue: () => {},
25+
parseLiteral: () => {},
26+
});
27+
28+
expect(result).to.have.all.keys(_.keys(expectResult));
29+
});
30+
31+
it('converted GraphQLScalarType can validate query', async () => {
32+
const EmailType = joiToStringScalaType('email', Joi.string().email());
33+
34+
const schema = new GraphQLSchema({
35+
query: new GraphQLObjectType({
36+
name: 'RootQueryType',
37+
fields: {
38+
echo: {
39+
type: GraphQLString,
40+
args: {
41+
email: { type: EmailType },
42+
},
43+
resolve: (root, {email}) => {
44+
return email;
45+
},
46+
},
47+
},
48+
}),
49+
});
50+
51+
let query = `
52+
query {
53+
echo (email: "hiexample.com")
54+
}
55+
`;
56+
57+
let result = await graphql(schema, query);
58+
expect(result.errors).to.have.length(1);
59+
60+
61+
query = `
62+
query {
63+
echo (email: "[email protected]")
64+
}
65+
`;
66+
67+
result = await graphql(schema, query);
68+
expect(result.errors).to.be.empty;
69+
});
70+
});
71+
});

src/utilities/typeConverter.js

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { GraphQLScalarType, GraphQLError } from 'graphql';
2+
import { Kind } from 'graphql/language';
3+
import assert from 'assert';
4+
import _ from 'lodash';
5+
import Joi from 'Joi';
6+
7+
export function joiToStringScalaType(name, schema) {
8+
assert(!_.isEmpty(name), 'required name argument');
9+
assert(schema.isJoi, 'joi schema required');
10+
11+
return new GraphQLScalarType({
12+
name,
13+
serialize: value => {
14+
return value;
15+
},
16+
parseValue: value => {
17+
return value;
18+
},
19+
parseLiteral: ast => {
20+
if (ast.kind !== Kind.STRING) {
21+
throw new GraphQLError('Query error: Can only parse strings got a: ' + ast.kind, [ast]);
22+
}
23+
let value;
24+
try {
25+
value = Joi.attempt(ast.value, schema);
26+
} catch (err) {
27+
throw new GraphQLError(err.message);
28+
}
29+
return value;
30+
},
31+
});
32+
}

0 commit comments

Comments
 (0)