Created
January 13, 2016 18:58
-
-
Save dphaener/a5c0a6ab87cb2297483f to your computer and use it in GitHub Desktop.
A sample custom network layer for Relay
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
import Relay from 'react-relay' | |
import fetch from 'isomorphic-fetch' | |
export default class NetworkLayer { | |
constructor(auth, url = null) { | |
this.auth = auth | |
this.url = url || 'http://localhost:7000/queries' | |
} | |
get defaultHeaders() { | |
return { | |
'Authorization': `Token ${this.auth}`, | |
'Accept': '*/*', | |
'Content-Type': 'application/json' | |
} | |
} | |
buildRequest(request) { | |
return JSON.stringify({ | |
query: request.getQueryString(), | |
variables: request.getVariables() | |
}) | |
} | |
sendMutation(request) { | |
return fetch(this.url, { | |
method: 'POST', | |
body: this.buildRequest(request), | |
headers: this.defaultHeaders | |
}). | |
then(response => response.json()). | |
then(results => { | |
if (results.errors) { | |
request.reject(new Error(this.formatRequestErrors(results.errors, request))) | |
} else { | |
request.resolve({ response: results.data }) | |
} | |
}) | |
} | |
sendQueries(requests) { | |
return Promise.all(requests.map( | |
request => fetch(this.url, { | |
method: 'POST', | |
body: this.buildRequest(request), | |
headers: this.defaultHeaders | |
}). | |
then(response => response.json()). | |
then(results => { | |
if (results.errors) { | |
request.reject(new Error(this.formatRequestErrors(results.errors, request))) | |
} else { | |
request.resolve({ response: results.data }) | |
} | |
}) | |
)) | |
} | |
supports(options) { | |
return false | |
} | |
formatRequestErrors(errors, request) { | |
let CONTEXT_BEFORE = 20, | |
CONTEXT_LENGTH = 60, | |
queryLines = request.getQueryString().split('\n') | |
return errors.map(({locations, message}, ii) => { | |
var prefix = (ii + 1) + '. ' | |
var indent = ' '.repeat(prefix.length) | |
//custom errors thrown in graphql-server may not have locations | |
var locationMessage = locations ? | |
('\n' + locations.map(({column, line}) => { | |
var queryLine = queryLines[line - 1] | |
var offset = Math.min(column - 1, CONTEXT_BEFORE) | |
return [ | |
queryLine.substr(column - 1 - offset, CONTEXT_LENGTH), | |
' '.repeat(offset) + '^^^', | |
].map(messageLine => indent + messageLine).join('\n') | |
}).join('\n')) : | |
'' | |
return prefix + message + locationMessage | |
}).join('\n') | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment