// contentType is for the Request header's 'Content-Type'// responseType is for the Response header's 'Content-Type'// cf: https://developer.mozilla.org/en-US/docs/Web/API/Response#Methods// works for fetch or any other http clientconstdef={basePath: 'http://api.example.com',prefix: '/v0',// not requiredroutes: {'getUser': {// call nameuri: '/user/:id',// :id auto processed by 'call' and it's parametersmethod: 'get',responseType: 'json',},'createUser': {uri: '/user',method: 'post',contentType: 'application/xml',// I know xml sucks, it's just an exampleresponseType: 'json',},
...
},};
Instantiate
// app.config.jsimportWrappyfrom'api-wrappy';// wrapper inside node_modulesimportdeffrom'./def.js';constwrapper=newWrappy(def);// OR directly define, whateverconstwrapper=newWrappy({...});exportdefaultwrapper;
Use
importwrapperfrom'./app.config.js';asyncfunctionapiCalls(){try{wrapper.call('getUser',{id: 24}).then((user)=>{
...
});}catch(err){// handle errorconsole.log('Error: ',err);}// ORwrapper.call('getUser',{id: 24})// still works as async returns a promise.then((user)=>{...}).catch((e)=>{// handle not found or whateverconsole.log('Error: ',err);});// ORtry{constuser=awaitwrapper.call('getUser',{id: 24});constuserList=awaitwrapper.call('createUser',{headers: {Authorization: 'Bearer <ANiceToken>'},body: {name: 'Foo'},});//ORconstret=wrapper.callMultiple([wrapper.call('getUser',{id: 24}),wrapper.call('createUser',{...}),
...
]);// ret = [response for getUser, response for createUser, ...]; <- Very powerful}catch(err){console.log('Error: ',err);// Errors are caught, allelujah!}}
About
A simple, flexible and easy to use webservice wrapper for npm