Skip to content

Instantly share code, notes, and snippets.

@ianfabs
Created October 22, 2018 04:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ianfabs/cd5756f7749769e8aa88bb6ebeb07cba to your computer and use it in GitHub Desktop.
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
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);
}
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