Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simple urn directive example #6

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 1 addition & 9 deletions experiments/graphql-tools-mocking.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,10 @@

## Setup

This assumes we are using volta.

Install `ts-node`:

```sh
$ volta install ts-node
```

Run the demo (that includes a server) by running:

```sh
$ ts-node graphql-tools-mocking/index.ts
$ yarn ts-node graphql-tools-mocking/index.ts
```

You should be able to see the result of the query that was executed directly.
Expand Down
73 changes: 69 additions & 4 deletions graphql-tools-mocking/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { makeExecutableSchema } from '@graphql-tools/schema';
import { addMocksToSchema } from '@graphql-tools/mock';
import { graphql } from 'graphql';
import { mapSchema, getDirective, MapperKind } from '@graphql-tools/utils';
import { graphql, GraphQLSchema, defaultFieldResolver } from 'graphql';
import { faker } from '@faker-js/faker';
import { createServer } from '@graphql-yoga/node';

Expand All @@ -15,6 +16,7 @@ const schemaString = `
description: String
date: Date
author: BookAuthor
urn: String @urn(type: "foo", fields: [{ name: "first" }, { name: "last" }])
}

type BookAuthor {
Expand All @@ -35,8 +37,68 @@ const schemaString = `
}
`;

let id = 1;

function idGenerator() {
return id++;
}

function urnDirective(schema: GraphQLSchema): GraphQLSchema {
const directiveName = 'urn';

return mapSchema(schema, {
[MapperKind.OBJECT_FIELD]: (fieldConfig) => {
const urnDirectiveArgs = getDirective(
schema,
fieldConfig,
directiveName
)?.[0] as
| {
type: string;
fields?: [];
}
| undefined;

if (urnDirectiveArgs) {
const { resolve = defaultFieldResolver } = fieldConfig;

return {
...fieldConfig,
resolve: async function (source, args, context, info) {
const result = await resolve(source, args, context, info);

if (typeof result === 'string') {
const { type, fields = [] } = urnDirectiveArgs;

const baseUrn = `unique_urn_with_parts_${type}`;

if (fields.length) {
return `${baseUrn}:(${fields.map(() => idGenerator())})`;
}

return baseUrn;
}
Comment on lines +62 to +80
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks good for our purposes, but WDYT about having the pattern be regex based so it's more widely applicable than just URNs?


return result;
},
};
}
},
});
}

const urnDirectiveTypeDef = () => `
directive @urn(type: String!, fields: [FieldMetadata!]) on FIELD_DEFINITION

input FieldMetadata {
name: String
}
`;

// Make a GraphQL schema with no resolvers
const schema = makeExecutableSchema({ typeDefs: schemaString });
const schema = makeExecutableSchema({
typeDefs: [schemaString, urnDirectiveTypeDef()],
});

// Create a new schema with mocks
const schemaWithMocks = addMocksToSchema({
Expand All @@ -58,9 +120,11 @@ const schemaWithMocks = addMocksToSchema({
},
});

const schemaWithUrnDirective = urnDirective(schemaWithMocks);

// optionally we can serve the schema in the network
const server = createServer({
schema: schemaWithMocks,
schema: schemaWithUrnDirective,
});

server.start();
Expand All @@ -71,6 +135,7 @@ const query = /* GraphQL */ `
id
description
date
urn
author {
id
firstName
Expand All @@ -82,7 +147,7 @@ const query = /* GraphQL */ `
`;

graphql({
schema: schemaWithMocks,
schema: schemaWithUrnDirective,
source: query,
}).then((result) => {
console.log('Got result %o', result);
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@
"graphql": "^16.5.0",
"graphql-faker": "^2.0.0-rc.25",
"graphql-mocks": "^0.8.4",
"prettier": "^2.7.1"
"prettier": "^2.7.1",
"ts-node": "^10.9.1"
},
"dependencies": {
"typescript": "^4.8.2"
Expand Down
9 changes: 9 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"esModuleInterop": true,
"strict": true,
"skipLibCheck": true
}
}
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -3268,7 +3268,7 @@ tr46@~0.0.3:
resolved "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a"
integrity sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==

ts-node@^10.5.0:
ts-node@^10.5.0, ts-node@^10.9.1:
version "10.9.1"
resolved "https://registry.yarnpkg.com/ts-node/-/ts-node-10.9.1.tgz#e73de9102958af9e1f0b168a6ff320e25adcff4b"
integrity sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==
Expand Down