Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
oleg-koval committed Jan 11, 2018
0 parents commit f623c15
Show file tree
Hide file tree
Showing 14 changed files with 1,515 additions and 0 deletions.
25 changes: 25 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"extends": [
"warp/node",
"warp/es6"
],
"parserOptions": {
"ecmaVersion": 8,
"sourceType": "module"
},
"rules": {
"semi": "off",
"semi-style": "off",
"object-curly-spacing": [
"error",
"always"
],
"line-comment-position": "off",
"func-style": "off",
"no-use-before-define": "off",
"no-console": "off",
"max-len": "off",
"no-debugger": "warn",
"complexity": "warn"
}
}
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/node_modules/
/.envrc
.DS_Store
11 changes: 11 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
sudo: required

services:
- docker

language: node_js

script: "npm test"

node_js:
- "8"
19 changes: 19 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
The MIT License (MIT)
Copyright (c) 2018-present Wearereasonablepeople B.V.

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
# Trembita.js

[![Build Status](https://travis-ci.com/wearereasonablepeople/trembita.svg?token=H11zxJynPszpg8G3VJzP&branch=master)](https://travis-ci.com/wearereasonablepeople/trembita)

# Description
42 changes: 42 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
const Promise = require('bluebird');

const {
generateErrorMessage
} = require('./units');
const request = Promise.promisify(require('request'));

const RequestClient = class RequestClient {
constructor(options) {
this.raw = options => {
const expectedCodes = options.expectedCodes || [200];
return this.client(options)
.then(res => {
if (!expectedCodes.includes(res.statusCode)) {
const msg = generateErrorMessage(res, options)
const error = new Error(msg);
error.httpStatusCode = res.statusCode;
error.httpBody = res.body;
throw new Error(error);
}
if (res.body === undefined) {
res.body = null
}
return res.body;
})
.catch(this.log.error)
}
this.request = options => this.raw(options);
if (!options.endpoint) {
throw new Error('no endpoint');
}

this.endpoint = options.endpoint;
this.log = options.log || console;
this.client = request.defaults({
baseUrl: this.endpoint,
json: true,
});
}
};

module.exports = RequestClient;
25 changes: 25 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
{
"name": "trembita",
"version": "1.0.0",
"private": true,
"description": "",
"main": "index.js",
"scripts": {
"test": "mocha",
"lint": "eslint *.js"
},
"author": "Oleg Koval <[email protected]> (http://wearereasonablepeople.com/)",
"license": "MIT",
"dependencies": {
"bluebird": "^3.0.6",
"ramda": "^0.25.0",
"request": "^2.67.0"
},
"devDependencies": {
"chai": "^4.1.2",
"eslint": "^4.8.0",
"eslint-config-warp": "^2.1.0",
"mocha": "^4.1.0",
"nock": "^9.1.6"
}
}
9 changes: 9 additions & 0 deletions test/helpers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
const noop = function() {};

module.exports.log = {
trace: noop,
debug: noop,
info: noop,
warn: console.warn.bind(console),
error: noop
};
95 changes: 95 additions & 0 deletions test/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
const { should, expect } = require('chai');
const nock = require('nock');
const helpers = require('./helpers');

const Trembita = require('../');

describe('Trembita:', () => {
let scope;
const clientOptions = {
endpoint: 'https://example.com/api',
log: helpers.log
};

before(() => { return tbita = new Trembita(clientOptions); });
beforeEach(() => {
// set up an HTTP mock
return scope = nock(clientOptions.endpoint);
});
afterEach(() => { return scope.done(); });

it(
'should be created with six properties: raw, request, endpoint, log, client', () => {
expect(tbita).to.have.property('raw');
expect(tbita).to.have.property('request');
expect(tbita).to.have.property('endpoint');
expect(tbita).to.have.property('log');
expect(tbita).to.have.property('client');
});

it('should return status code 200 and resourse', () => {
scope
.get('/users?page=2')
.replyWithFile(200, __dirname +
'/responses/get-users-page-2.json')

return tbita
.request({
url: '/users',
qs: {
page: 2
},
expectedCodes: [200]
})
.then(res => {
expect(res).to.deep.equal({
page: 2,
per_page: 3,
total: 12,
total_pages: 4,
data: [{
id: 4,
first_name: 'fName',
last_name: 'lName'
},
{
id: 5,
first_name: 'fName',
last_name: 'lName'
},
{
id: 6,
first_name: 'fName',
last_name: 'lName'
}]
})
});
});

it('should return 404 status code', () => {
scope
.get('/profiles')
.reply(404)

return tbita
.request({
url: '/profiles',
expectedCodes: [404]
})
});

it('should return error related to unexpected status code', () => {
scope
.get('/profiles/1')
.reply(404)

return tbita
.request({
url: '/profiles/1',
expectedCodes: [200]
})
.catch(err => {
expect(err).to.throw
})
});
});
3 changes: 3 additions & 0 deletions test/mocha.opts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
--reporter spec
--recursive
--bail
23 changes: 23 additions & 0 deletions test/responses/get-users-page-2.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"page": 2,
"per_page": 3,
"total": 12,
"total_pages": 4,
"data": [
{
"id": 4,
"first_name": "fName",
"last_name": "lName"
},
{
"id": 5,
"first_name": "fName",
"last_name": "lName"
},
{
"id": 6,
"first_name": "fName",
"last_name": "lName"
}
]
}
38 changes: 38 additions & 0 deletions test/units.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
const {
should, expect
} = require('chai');
const helpers = require('./helpers');
const {
generateErrorMessage
} = require('../units');


describe('Units:', () => {
it(
'should generate error message from response parameters and request options', () => {
const res = {
statusCode: 503,
body: {
key: 'value'
}
};
const options = {
option: 'value'
};
const actual = generateErrorMessage(res, options);
const expected =
`Unexpected status code: 503, Body: { key: \'value\' }, Options: { option: \'value\' }`;

expect(actual).to.be.equal(expected);
});
it(
'should fail with wrong input', () => {
const res = {
statusCode: 503,
body: {
key: 'value'
}
};
expect(() => {generateErrorMessage(res)}).to.throw('options object missing');
});
});
23 changes: 23 additions & 0 deletions units.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
const { is } = require('ramda');
const util = require('util');

/**
* Generate error message from response parameters and request options
* @method generateErrorMessage
* @param {Object} res response object
* @param {Object} options request options
* @return {String} Error message
*/
const generateErrorMessage = (res, options) => {
if (!is(Object, res)) {
throw new Error('response object missing')
}
if (!is(Object, options)) {
throw new Error('options object missing')
}
return `${`Unexpected status code: ${res.statusCode}, Body: ${util.inspect(res.body, { depth: 4 })}, Options: `}${util.inspect(options, { depth: 4 })}`
}

module.exports = {
generateErrorMessage
}
Loading

0 comments on commit f623c15

Please sign in to comment.