Created
October 22, 2018 04:18
-
-
Save ianfabs/cd5756f7749769e8aa88bb6ebeb07cba to your computer and use it in GitHub Desktop.
jgraph: a simple typescript-based fetch api for GraphQL, to make it a bit easier to use semantically
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
interface JraphOptions{ | |
url: string; | |
method: "post" | "POST" | "get" | "GET" | "put" | "PUT" | "delete" | "DELETE"; | |
query: string; | |
} | |
async function jraph(argv: JraphOptions){ | |
let url = argv.url; | |
let headers = { 'Content-Type': 'application/json' } | |
let body = JSON.stringify({query: argv.query}); | |
let fetch_options = { | |
method: argv.method, | |
headers, | |
body | |
}; | |
//returns request as JSON | |
// return (await fetch(url, fetch_options).then(res=>res.json())).data; | |
return fetch(url, fetch_options).then(res=>res.json()); | |
} | |
//Example | |
try{ | |
const result = await jraph({ | |
url: 'http://localhost:4000/graphql', | |
method: 'POST', | |
query: '{language}' | |
}); | |
console.dir(result); | |
// result in the console should be `{ data: {langauge: "GraphQL"} }` | |
// according to my example GraphQL server, which looks like the other file in this gist | |
}catch(e){ | |
console.error('err', e); | |
} |
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
const express = require('express'); | |
const { graphql, buildSchema } = require('graphql'); | |
const graphqlHTTP = require('express-graphql'); | |
const cors = require('cors'); | |
const schema = buildSchema(` | |
type Query { | |
language: String | |
} | |
`) | |
const rootValue = { | |
language: () => 'GraphQL' | |
} | |
const app = express() | |
app.use(cors()) | |
app.use('/graphql', graphqlHTTP({ | |
rootValue, schema, graphiql: true | |
}) | |
) | |
app.listen(4000, () => console.log('Listening on 4000')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment