UNPKG

forchange-api

Version:
103 lines (96 loc) 2.65 kB
const co = require('co'); const APIs = require('st-api').APIs; const HttpClient = require('st-api').HttpClient; const assessApiConfig = require('./config/assess.api.config'); const bookApiConfig = require('./config/book.api.config'); /* eslint camelcase:0 */ const __instance = (function () { let instance = null; return (_ins) => { if (_ins) { instance = _ins; } return instance; }; })(); let apis = {}; let bookTokenModel = null; let assessTokenModel = null; class ExamModel { constructor(opts) { if (__instance()) { return __instance(); } __instance(this); } static config(opts) { assessApiConfig.defaultHost = opts.assessHost; bookApiConfig.defaultHost = opts.bookHost; let httpClient = new HttpClient(); let _assessapis = new APIs(assessApiConfig, httpClient); let _bookapis = new APIs(bookApiConfig, httpClient); Object.assign(apis, _assessapis, _bookapis); bookTokenModel = opts.bookTokenModel; assessTokenModel = opts.assessTokenModel; } getExamList(page, per_page) { return co(function* () { if (!(bookTokenModel && apis.examList)) { throw new Error( 'You must config ExamModel with ExamModel.config(options) before use this method.' ); } let token = yield bookTokenModel.getToken(); page = page || 1; per_page = per_page || 10; let qs = { page, per_page, token }; let data = yield apis.examList.get(qs); // 这里应该用 error code 判断,但暂时接口文档没有 if (!data.data) { throw new Error(`An error occured when request ${apis.examList.url}`); } return { exams: data.data, total: data.meta.pagination.total, count: data.meta.pagination.count, per_page: data.meta.pagination.per_page, current_page: data.meta.pagination.current_page, total_pages: data.meta.pagination.total_pages }; }); } getExamScore(book_ids) { return co(function* () { if (!(assessTokenModel && apis.examScore)) { throw new Error( 'You must config ExamModel with ExamModel.config(options) before use this method.' ); } if (!Array.isArray(book_ids)) { throw new Error('book_ids must be an instance of Array.'); } let token = yield assessTokenModel.getToken(); let body = { book_ids }; let data = yield apis.examScore.post(body); if (!data.data) { throw new Error(`An error occured when request ${apis.examScore.url}`); } let list = data.data; let result = []; for (let key in list) { let temp = {}; temp.id = parseInt(key, 10); temp.score = list[key]; result.push(temp); } return result; }); } } module.exports = ExamModel;