Skip to content

Instantly share code, notes, and snippets.

@olafkotur
Created February 3, 2020 15:33
Show Gist options
  • Save olafkotur/882413fc41a1fc19d263997879853ce0 to your computer and use it in GitHub Desktop.
Save olafkotur/882413fc41a1fc19d263997879853ce0 to your computer and use it in GitHub Desktop.
Simplified service for http requests in Typescript using the request library
const request = require('request');
export const HttpService = {
get: async (uri: string): Promise<any> => {
return await new Promise((resolve: any, reject: any) => {
request.get({ uri }, (error: Error, _response: any, body: any) => {
if (error) {
console.error(error);
reject();
}
try {
resolve(JSON.parse(body));
} catch(e) {
resolve({});
}
});
});
},
post: async (uri: string, body: any): Promise<any> => {
const options = {
uri,
form: body,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
};
return await new Promise((resolve: any, reject: any) => {
request.post(options, (error: Error, _response: any, body: any) => {
if (error) {
console.error(error);
reject();
}
try {
resolve(JSON.parse(body));
} catch(e) {
resolve({});
}
});
});
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment