Skip to content

Instantly share code, notes, and snippets.

@jenol
Last active February 10, 2022 14:45
Show Gist options
  • Save jenol/2e3157e78563f58124544e140d5b59f5 to your computer and use it in GitHub Desktop.
Save jenol/2e3157e78563f58124544e140d5b59f5 to your computer and use it in GitHub Desktop.
Example of how you can create a mock server using an existing servers introspection info.
const express = require('express');
const { graphqlHTTP } = require('express-graphql');
const { getIntrospectionQuery, buildClientSchema } = require('graphql');
const { request } = require('graphql-request');
const fs = require("fs");
const util = require("util");
const mocker = require('easygraphql-mock');
const token = "user your own";
(async () => {
try {
const schemaFilePath = __dirname + "/schema.json";
let result = null;
if (fs.existsSync(schemaFilePath)) {
result = JSON.parse((await util.promisify(fs.readFile)(schemaFilePath, { encoding: "utf-8" })).toString());
} else {
result = await request({
url: "https://api.github.com/graphql",
document: getIntrospectionQuery(),
variables: {},
requestHeaders: {
Authorization: `bearer ${token}`
},
});
await util.promisify(fs.writeFile)(schemaFilePath, JSON.stringify(result, null, 4), { encoding: "utf-8" })
}
const schema = buildClientSchema(result);
const rootValue = {
repository: async (args, { schemaCode }) => {
const mock = mocker(schemaCode, {
Repository: {
name: args.name
},
RepositoryOwner: {
login: args.owner
}
})
return mock.Repository;
}
};
const app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: rootValue,
graphiql: true,
context: { schemaCode: result }
}));
app.listen(5000);
console.log('Running a GraphQL API server at http://localhost:5000/graphql');
} catch (e) {
console.error(e)
}
})();
@jenol
Copy link
Author

jenol commented Feb 10, 2022

query

query {
  repository (owner: "Betsson", name:"a") {
    name
    isPrivate
   	diskUsage
 		hasProjectsEnabled
    owner {
      login
    }
  }
}

Should return:

{
  "data": {
    "repository": {
      "name": "a",
      "isPrivate": false,
      "diskUsage": 4,
      "hasProjectsEnabled": true,
      "owner": {
        "login": "Betsson"
      }
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment