Skip to content

Commit

Permalink
Add a test for formatting dates with field arguments.
Browse files Browse the repository at this point in the history
  • Loading branch information
benjamn committed Mar 15, 2018
1 parent 402b59c commit d5577e4
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 1 deletion.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@
},
"devDependencies": {
"@types/chai": "4.0.10",
"@types/dateformat": "^1.0.1",
"@types/graphql": "0.11.7",
"@types/mocha": "^2.2.44",
"@types/node": "^8.0.47",
Expand Down
60 changes: 59 additions & 1 deletion src/test/testDirectives.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,8 @@ import {
GraphQLInt,
} from 'graphql';

import formatDate = require('dateformat');

const typeDefs = `
directive @schemaDirective(role: String) on SCHEMA
directive @enumValueDirective on ENUM_VALUE
Expand Down Expand Up @@ -590,7 +592,7 @@ describe('@directives', () => {
field.type = GraphQLString;
field.resolve = async function (...args: any[]) {
const date = await resolve.apply(this, args);
return require('dateformat')(date, format);
return formatDate(date, format);
};
}
}
Expand All @@ -616,6 +618,62 @@ describe('@directives', () => {
});
});

it('can be used to implement the @formattableDate example', async () => {
class FormattableDateDirective extends SchemaDirectiveVisitor {
public visitFieldDefinition(field: GraphQLField<any, any>) {
const { resolve = defaultFieldResolver } = field;

field.args.push({
name: 'format',
type: GraphQLString,
defaultValue: 'mmmm d, yyyy',
});

field.type = GraphQLString;
field.resolve = async function (source, { format, ...args }, context, info) {
const date = await resolve.call(this, source, args, context, info);
return formatDate(date, format);
};
}
}

const schema = makeExecutableSchema({
typeDefs: `
directive @formattableDate on FIELD_DEFINITION
scalar Date
type Query {
today: Date @formattableDate
}`,

schemaDirectives: {
formattableDate: FormattableDateDirective
},

resolvers: {
Query: {
today() {
return new Date(1521131357195);
}
}
}
});

assert.deepEqual(
(await graphql(schema, `query { today }`)).data,
{ today: 'March 15, 2018' }
);

assert.deepEqual(
(await graphql(schema, `
query {
today(format: "dd mmm yyyy")
}`)).data,
{ today: '15 Mar 2018' }
);
});

it('can be used to implement the @intl example', () => {
function translate(
text: string,
Expand Down

0 comments on commit d5577e4

Please sign in to comment.