Created
February 3, 2020 15:33
-
-
Save olafkotur/882413fc41a1fc19d263997879853ce0 to your computer and use it in GitHub Desktop.
Simplified service for http requests in Typescript using the request library
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
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