From f1ec45d9138aee2a8f630efc05aa0f32ebb3c801 Mon Sep 17 00:00:00 2001 From: Wessel Tip Date: Mon, 8 Jul 2019 13:05:13 +0200 Subject: [PATCH] Add profiles --- lib/index.js | 34 +++++++++++++++++++++++++++------- lib/util/Collection.js | 21 +++++++++++++++++++++ 2 files changed, 48 insertions(+), 7 deletions(-) create mode 100644 lib/util/Collection.js diff --git a/lib/index.js b/lib/index.js index c9d6716..e198d53 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,15 +1,35 @@ const req = require('./model/WumpRequest'); -const common = [ 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH' ]; const metaData = require('../package.json'); +const Collection = require('./util/Collection'); -module.exports = (url, method) => { return new req(url, method); }; +const profiles = new Collection(); -for (const method of common) { - module.exports[method.toLowerCase()] = (url, method) => { - if (typeof url === 'string') return new req(url, { method: method, ...method }); - else return new req({ method: method, ...url }, method); +module.exports.default = {}; +module.exports.setDefault = (profileData = {}) => this.default = profileData; + +module.exports = (url, method = this.default) => { + if (url instanceof Object) url = Object.assign(this.default, url); + return new req(url, method); +}; + +module.exports.getProfile = (name = 'main') => { return profiles.get(name); }; +module.exports.setProfile = (name = 'main', profileData = {}) => { + if (typeof profileData !== 'object') throw new TypeError(`profileData must be of type object. Received type ${typeof profileData}`); + if (typeof name !== 'string') throw new TypeError(`name must be of type string. Recevied type ${typeof name}`); + return profiles.set(name, profileData); +}; + +for (const entry of [ 'GET', 'HEAD', 'POST', 'PUT', 'DELETE', 'CONNECT', 'OPTIONS', 'TRACE', 'PATCH' ]) { + module.exports[entry.toLowerCase()] = (url, method = { method: entry }) => { + if (typeof url === 'object') { + url = Object.assign(this.default, url); + url.method = entry; + } + + return new req(url, method); }; } module.exports.version = metaData.version; -module.exports.userAgent = `${metaData.name}/${metaData.version} (${metaData.repository.url})`; \ No newline at end of file +module.exports.userAgent = `${metaData.name}/${metaData.version} (${metaData.repository.url})`; + diff --git a/lib/util/Collection.js b/lib/util/Collection.js new file mode 100644 index 0000000..5241e7b --- /dev/null +++ b/lib/util/Collection.js @@ -0,0 +1,21 @@ +module.exports = class PikminCollection extends Map { + constructor() { + super(); + } + + filter(callback) { + let result = []; + for (const entry of Array.from(this.values())) { + if (callback(entry)) result.push(entry); + } + + return result; + } + + map(callback) { + let result = []; + for (const value of Array.from(this.values())) result.push(callback(value)); + + return result; + } +}; \ No newline at end of file