diff --git a/.gitignore b/.gitignore index 17ef735..44a82f9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,4 +1,5 @@ node_modules .db.js package-lock.json -dbback.js \ No newline at end of file +dbback.js +yarn.lock \ No newline at end of file diff --git a/lib/db.js b/lib/db.js index a1fe32c..16f6ff3 100644 --- a/lib/db.js +++ b/lib/db.js @@ -1,13 +1,88 @@ -const Tapable = require('tapable') +const { AsyncSeriesWaterfallHook, SyncWaterfallHook } = require("tapable"); -class DB extends Tapable { +class HooksAdapter { constructor() { - // TODO + this.hooks = { + endpoint: new AsyncSeriesWaterfallHook(["options"]), + options: new SyncWaterfallHook(["options"]), + judge: new SyncWaterfallHook(["res"]), + }; } - request() { - // TODO + register(hookName, cb) { + switch (hookName) { + case "endpoint": + this.hooks.endpoint.tapPromise("requestPlugin", (options) => { + const result = cb(options); + if (result) { + return result.catch((err) => { + return Promise.reject(err); + }); + } else { + return Promise.resolve(options); + } + }); + break; + case "options": + this.hooks.options.tap("setOptionsPlugin", cb); + break; + case "judge": + this.hooks.judge.tap("parseResponsePlugin", cb); + break; + } + } + + request(options) { + return this.hooks.endpoint.promise(options).then(res => { + const judgeRes = this.hooks.judge.call(res); + + if (judgeRes === true) { + return Promise.reject(res); + } + + return res; + }).catch((err) => { + return Promise.reject(err); + }); + } + + syncOptions (options) { + this.hooks.options.call(options); + } +} + +class DB { + constructor(options) { + this.options = options || {}; + this.hooksAdapter = new HooksAdapter(); + + this.plugin = function (hookName, cb) { + this.hooksAdapter.register(hookName, cb); + }; + } + + request(options) { + if (options) { + this.modifyOptions(options); + } + + return this.hooksAdapter + .request(this.options) + .then((res) => { + return Promise.resolve(res); + }) + .catch((err) => { + return Promise.reject(err); + }) + } + + modifyOptions(options = {}) { + if (typeof options !== "object") { + throw new Error("argument should be a Object"); + } + Object.assign(this.options, options); + this.hooksAdapter.syncOptions(this.options) } } -module.exports = DB \ No newline at end of file +module.exports = DB; diff --git a/package.json b/package.json index aad5780..b26e5ce 100644 --- a/package.json +++ b/package.json @@ -4,7 +4,7 @@ "description": "test", "main": "index.js", "scripts": { - "test": "karma start" + "test": "jest" }, "repository": { "type": "git", @@ -20,6 +20,7 @@ }, "homepage": "https://github.com/FE-star/homework2#readme", "devDependencies": { + "jest": "^28.1.3", "karma": "^6.3.16", "karma-chrome-launcher": "^2.2.0", "karma-mocha": "^1.3.0", @@ -28,6 +29,7 @@ "webpack": "^3.5.3" }, "dependencies": { - "puppeteer": "^16.2.0" + "puppeteer": "^16.2.0", + "tapable": "^2.2.1" } }