Created
September 1, 2017 02:59
-
-
Save kanziw/81030712748af2f313525053b235973e to your computer and use it in GitHub Desktop.
server-to-server-request-sample
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
import request from 'request' | |
const requester = request.defaults({ | |
headers: { 'Content-Type': 'application/json, charset=utf8', 'Api-Token': 'sample-api-token' }, | |
baseUrl: 'https://sample.kanziw.github.io/v3', | |
json: true, | |
}) | |
/** | |
* @param options {object} | |
* @config method {'GET'|'POST'|'DELETE'|'PUT'} | |
* @param [errHandler] {function} | |
* @returns {Promise} | |
*/ | |
const requestHandler = (options, errHandler) => { | |
return new Promise((resolve, reject) => requester(options, (err, res, body) => { | |
err ? reject(err) : (body.error ? reject(body) : resolve(body)) | |
})).catch(ex => { | |
if (errHandler) { | |
errHandler(ex) | |
} else { | |
throw new Error(`[${ex.err_code}] ${ex.message}`) | |
} | |
}) | |
} | |
const requestToServer = { | |
get: (uri, errHandler) => requestHandler({ method: 'GET', uri }, errHandler), | |
post: (uri, body, errHandler) => requestHandler({ method: 'POST', uri, body }, errHandler), | |
del: (uri, errHandler) => requestHandler({ method: 'DELETE', uri }, errHandler), | |
put: (uri, body, errHandler) => requestHandler({ method: 'PUT', uri, body }, errHandler), | |
} | |
// Sample requset Examples | |
async sampleRequests () { | |
await requestToServer.get('/child-uri') | |
await requestToServer.post('/child-uri', {a: 1}) | |
await requestToServer.del('/child-uri', () => null) // ignore error sample | |
await requestToServer.put('/child-uri', {b: 2}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment