Skip to content

Instantly share code, notes, and snippets.

@wiktor256
Last active February 24, 2025 10:26
Show Gist options
  • Select an option

  • Save wiktor256/fede8f058dbdc1728910de8400c50c72 to your computer and use it in GitHub Desktop.

Select an option

Save wiktor256/fede8f058dbdc1728910de8400c50c72 to your computer and use it in GitHub Desktop.
Program that shows performance degradation of graphQL when resolver returns a promise.
/**
* Program that shows performance degradation of graphQL when resolver returns a promise.
* See Book.author() resolver below.
*
* Usage:
* (1) run graphQL query with synchronous resolver
* node gql-test limit=100000 async=0
* (2) run graphQL query with asynchronous resolver
* node gql-test limit=100000 async=1
* Sample results:
* sync resolver: 603.922ms
* async resolver: 2541.374ms
*/
const { graphql, buildSchema } = require('graphql');
function getIntArg(argName) {
const arg = process.argv.find(a => new RegExp(`^${argName}=`).test(a));
if (arg) {
return Number.parseInt(arg.split('=')[1], 10);
}
}
// Test arguments
const args = {
limit: getIntArg('limit') || 100000,
async: getIntArg('async') || false
};
const schema = buildSchema(`
type Author {
name: String!
}
type Book {
title: String!
author: Author!
}
type Query {
books(limit: Int!): [Book!]!
}
`);
class Author {
constructor(name) {
this.name = name;
}
}
const author = new Author('John Doe');
class Book {
constructor(title) {
this.title = title;
}
author() {
if (args.async) {
return Promise.resolve(author);
}
return author;
}
}
const root = {
books: ({limit}) => {
const books = [];
for (let i = 0; i < limit; i++) {
books.push(new Book('Book:' + i));
}
return Promise.resolve(books);
}
};
async function main() {
const testName = args.async ? 'async resolver' : 'sync resolver';
console.time(testName)
await graphql(schema, `
{
books(limit: ${args.limit}) {
title
author {
name
}
}
}
`, root);
console.timeEnd(testName);
}
main();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment