Last active
February 24, 2025 10:26
-
-
Save wiktor256/fede8f058dbdc1728910de8400c50c72 to your computer and use it in GitHub Desktop.
Program that shows performance degradation of graphQL when resolver returns a promise.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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