Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions example.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
'use strict';

const swapi = require('swapi-node');
const swapi = require('./lib/swapi-node');

swapi.getPerson().then(result => {
swapi.getPerson(4).then(result => {
return result.getStarships();
}).then(result => {
return result[0].getFilms();
}).then(result => {
console.log(result);
}).catch(error => {
console.log(error);
Expand Down
34 changes: 13 additions & 21 deletions lib/swapi-node.js
Original file line number Diff line number Diff line change
@@ -1,25 +1,18 @@
'use strict';

const request = require('request');
const fetch = require('node-fetch');
const util = require('./util');

const BASE_URL = 'https://swapi.dev/api/';
const PROTOCOL = 'https';
const HOST = 'swapi.dev';
const BASE_URL = `${PROTOCOL}://${HOST}/api/`;
const BASE_URL_REGEX = new RegExp(`http[s]?://${HOST}/api`);

function sendRequest (options) {
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if (error || response.statusCode > 399) {
return reject(new Error(response.statusCode));
}

let jsonBody;

try {
jsonBody = JSON.parse(body);
} catch {
return reject(new Error('JSON parse error'));
}

let {url, ...otherOptions} = options;
return fetch(url, otherOptions)
.then(response => response.json())
.then(jsonBody => {
['nextPage', 'previousPage'].forEach(value => {
jsonBody[value] = (() => {
return () => {
Expand All @@ -38,15 +31,15 @@ function sendRequest (options) {
jsonBody['get' + util.capitaliseFirstLetter(value)] = (() => {
return () => {
if (!Array.isArray(jsonBody[value])) {
if (jsonBody[value].includes(BASE_URL)) {
if (!!jsonBody[value].match(BASE_URL_REGEX)) {
return makeRequest(jsonBody[value]);
}

return Promise.resolve(jsonBody[value]);
}

const p = jsonBody[value].map(value_ => {
if (value_.includes(BASE_URL)) {
if (!!value_.match(BASE_URL_REGEX)) {
return makeRequest(value_);
}

Expand All @@ -59,14 +52,13 @@ function sendRequest (options) {
}
});

return resolve(jsonBody);
return jsonBody;
});
});
}

function makeRequest (url) {
const options = {
url: (url.includes(BASE_URL)) ? url : BASE_URL + url,
url: (!!url.match(BASE_URL_REGEX)) ? url : `${BASE_URL}${url}`,
headers: {
'User-Agent': 'swapi-node',
'SWAPI-Node-Version': require('../package.json').version
Expand Down
Loading