Last active
February 10, 2022 14:45
-
-
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.
This file contains 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
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) | |
} | |
})(); | |
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
package.json