Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
server-to-server-request-sample
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
You can’t perform that action at this time.