From d15fcc2503bec884b6479a26f4557d0d6abcf64b Mon Sep 17 00:00:00 2001 From: sundowndev Date: Thu, 30 Aug 2018 14:24:24 +0200 Subject: [PATCH] Api client class --- src/ApiClient.js | 70 ++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 src/ApiClient.js diff --git a/src/ApiClient.js b/src/ApiClient.js new file mode 100644 index 0000000..ae8e389 --- /dev/null +++ b/src/ApiClient.js @@ -0,0 +1,70 @@ +"use strict"; + +const request = require('request'); +const async = require('async'); + +export default function ApiClient() { + this.ApiUrl = ''; +} + +ApiClient.prototype.setApiUrl = function (url) { + ApiClient.ApiUrl = url; +}; + +ApiClient.prototype.sendRequest = function (method, resource, data, callback) { + async.parallel([ + function () { + request.get({ + "headers": {"content-type": "application/json"}, + "url": ApiClient.ApiUrl + resource, + "data": data + }, (error, response, body) => { + if(error) { console.log(err); callback(true); return; } + let obj = JSON.parse(body); + callback(false, obj); + }); + } + ]); +}; + +/** + * Find all posts + */ +ApiClient.prototype.findAllPosts = function () { + console.log(this.sendRequest('GET', '/posts', [])); + + this.sendRequest('GET', '/posts', [], function (result) { + return result; + }); +}; + +/** + * Find posts by user id + */ +ApiClient.prototype.findPostsByUser = function (userId) { + let posts = this.sendRequest('GET', '/posts', []); + + let postsOfUser = []; + + posts.forEach(function (p) { + if (p.userId === userId) { + postsOfUser.push(p); + } + }); + + return postsOfUser; +}; + +/** + * Find user by id + */ +ApiClient.prototype.findUserById = function (userId) { + return this.sendRequest('GET', '/users/'+userId, []); +}; + +/** + * Find comments by user id + */ +ApiClient.prototype.findCommentsByUserId = function () { + return this.sendRequest('GET', '/comments', []); +}; \ No newline at end of file