Commit 5497c147 authored by 何娜's avatar 何娜

学信H5开发完成

parents
Pipeline #6132 passed with stage
in 47 seconds
'use strict';
module.exports = {
write: true,
prefix: '^',
plugin: 'autod-egg',
test: [
'test',
'benchmark',
],
dep: [
'egg',
'egg-scripts',
],
devdep: [
'egg-ci',
'egg-bin',
'egg-mock',
'autod',
'autod-egg',
'eslint',
'eslint-config-egg',
'webstorm-disable-index',
],
exclude: [
'./test/fixtures',
'./dist',
],
};
{
"extends": [
"eslint-config-egg"
],
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true
}
},
"rules": {
"indent": ["error", 2],
"array-bracket-spacing": ["error", "never"],
"linebreak-style": "off"
}
}
\ No newline at end of file
logs/
npm-debug.log
yarn-error.log
node_modules/
package-lock.json
yarn.lock
coverage/
.idea/
run/
.DS_Store
*.sw*
*.un~
variables:
DOCKER_REGISTRY: 't-docker.51gjj.com'
before_script:
- docker login -u pengtianzi -p 4dc8b3a4d91fa7fa $DOCKER_REGISTRY
stages:
- pre_deploy
build_docker_image:
stage: pre_deploy
script:
- export IMAGE_TAG=${CI_COMMIT_TAG:-latest}
- docker build -t $DOCKER_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME:$IMAGE_TAG .
- docker push $DOCKER_REGISTRY/$CI_PROJECT_NAMESPACE/$CI_PROJECT_NAME:$IMAGE_TAG
tags:
- docker-image-builder
sudo: false
language: node_js
node_js:
- '8'
install:
- npm i npminstall && npminstall
script:
- npm run ci
after_script:
- npminstall codecov && codecov
sudo: false
language: node_js
node_js:
- '8'
install:
- npm i npminstall && npminstall
script:
- npm run ci
after_script:
- npminstall codecov && codecov
FROM t-docker.51gjj.com/tools/node:8.12.0
ENV LANG C.UTF-8
ENV NODE_ENV production
ENV PATH $PATH:/usr/local/node/bin/
RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY package.json /usr/src/app/
RUN yarn config set registry "https://registry.npm.taobao.org/"
RUN yarn install
COPY . /usr/src/app
EXPOSE 7001
CMD [ "yarn", "docker" ]
# it_h5_server
公积金H5认证服务
## QuickStart
<!-- add docs here for user -->
see [egg docs][egg] for more detail.
### Development
```bash
$ npm i
$ npm run dev
$ open http://localhost:7001/
```
### Deploy
```bash
$ npm start
$ npm stop
```
### npm scripts
- Use `npm run lint` to check code style.
- Use `npm test` to run unit test.
- Use `npm run autod` to auto detect dependencies upgrade, see [autod](https://www.npmjs.com/package/autod) for more detail.
[egg]: https://eggjs.org
\ No newline at end of file
# xuexin_h5
学信H5认证服务
## 快速入门
<!-- 在此次添加使用文档 -->
如需进一步了解,参见 [egg 文档][egg]
### 本地开发
```bash
$ npm i
$ npm run dev
$ open http://localhost:7001/
```
### 部署
```bash
$ npm start
$ npm stop
```
### 单元测试
- [egg-bin] 内置了 [mocha], [thunk-mocha], [power-assert], [istanbul] 等框架,让你可以专注于写单元测试,无需理会配套工具。
- 断言库非常推荐使用 [power-assert]
- 具体参见 [egg 文档 - 单元测试](https://eggjs.org/zh-cn/core/unittest)
### 内置指令
- 使用 `npm run lint` 来做代码风格检查。
- 使用 `npm test` 来执行单元测试。
- 使用 `npm run autod` 来自动检测依赖更新,详细参见 [autod](https://www.npmjs.com/package/autod)
[egg]: https://eggjs.org
'use strict';
const Controller = require('egg').Controller;
class OrderController extends Controller {
constructor(ctx) {
super(ctx);
this.createRule = {
appKey: 'string',
userId: {
type: 'string',
required: false,
},
orderId: {
type: 'string',
required: false,
format: /^(\w{8})-(\w{4})-(\w{4})-(\w{4})-(\w{12})$/,
message: '订单号格式错误',
}
};
this.partnerOrderRule = {
sign: 'string',
params: {
type: 'object',
rule: {
token: 'string',
appKey: 'string',
timestamp: 'string',
},
},
};
this.showRule = {
sign: 'string',
params: {
type: 'object',
rule: {
token: 'string',
orderSn: 'string',
appKey: 'string',
timestamp: 'string',
},
},
};
}
async create() {
const { ctx, service } = this;
ctx.validate(this.createRule);
let { appKey, userId, notifyUrl, backUrl, orderId } = ctx.request.body;
const appKeyInfo = await service.partner.fetchInfo(appKey);
ctx.logger.info(appKey, ',appKeyInfo,', appKeyInfo);
if (!(appKeyInfo && appKeyInfo.valid === true && appKeyInfo.enableIt === true)) {
return ctx.fail('未开通此服务');
}
const object = {
orderId,
taskId: '',
userId: userId || '',
cityId: '',
notifyUrl: notifyUrl || (ctx.app.notifyMap && ctx.app.notifyMap.get(appKey) && ctx.app.notifyMap.get(appKey).notifyUrl) || '',
backUrl: backUrl || '',
appkey: appKey,
status: 'init',
};
if (orderId) {
await service.order.update(object);
} else {
object.orderId = ctx.helper.getUuid();
await service.order.create(object);
}
ctx.success({ orderId: object.orderId });
}
async partnerOrder() {
const {ctx, service} = this;
ctx.validate(this.partnerOrderRule);
const {appKey} = ctx.request.body.params;
const result = await service.signature.partnerOrderId(ctx.request.body);
await service.order.create({
orderId: result.data.orderSn,
taskId: '',
userId: '',
cityId: '',
appkey: appKey,
status: 'init',
});
ctx.success(result);
}
async partnerData() {
const {ctx, service} = this;
ctx.validate(this.showRule);
const {appKey, orderSn} = ctx.request.body.params;
await service.signature.signatureCheck(ctx.request.body);
const data = await service.order.getOneByOrderId(orderSn);
if (data && data.status === 'success') {
const result = await service.storage.read(orderSn, appKey);
ctx.body = {
code: 0,
data: result
};
return;
}
ctx.body = {
code: -1,
message: '无此订单号'
};
}
async orderShow() {
const { ctx, service } = this;
const { appKey, orderId } = ctx.params;
const appKeyInfo = await service.partner.fetchInfo(appKey);
if (!(appKeyInfo && appKeyInfo.valid === true && appKeyInfo.enableItView === true)) {
return ctx.fail('未开通此服务');
}
const data = await service.order.getOneByOrderId(orderId);
if (data) {
if (data.status === 'success' && (data.appkey === appKey)) {
const result = await service.storage.read(orderId, appKey);
// const ret = service.washData.dealData(result);
ctx.success(result);
return;
}
}
ctx.fail('无此订单号');
}
}
module.exports = OrderController;
\ No newline at end of file
'use strict';
const Controller = require('egg').Controller;
class PartnerController extends Controller {
async show() {
const { ctx, service } = this;
const { appKey } = ctx.params;
const ret = await service.partner.fetchTheme(appKey);
if (ret && ret.appKey === appKey) {
ctx.success(ret);
return;
}
ctx.fail('尚未配置主题');
}
async fetchAgreements() {
const { ctx, service } = this;
const { id } = ctx.params;
const ret = await service.partner.fetchAgreements(id);
if (ret && String(ret.id) === id) {
ctx.success(ret);
return;
}
ctx.fail('未获取到协议');
}
}
module.exports = PartnerController;
'use strict';
const Controller = require('egg').Controller;
class ScriptController extends Controller {
async fetchScripts() {
const { ctx, service } = this;
const { appKey } = ctx.query;
let limitScriptsList = false;
if (appKey) {
const ret = await service.partner.fetchInfo(appKey);
if (ret) {
limitScriptsList = ret.itExcludeScripts;
}
}
let data = await service.scripts.fetchScripts();
if (limitScriptsList) {
data = data.filter(item => {
return !(limitScriptsList.includes(item.id))
});
}
ctx.success(data);
}
async fetchOneScripts() {
const { ctx, service } = this;
let { scriptId } = ctx.params;
if (scriptId === 'auto') {
const ret = await service.scripts.fetchScriptIdByIp();
scriptId = ret.scriptId;
}
const data = await service.scripts.fetchOneScripts(scriptId);
ctx.success(data);
}
async fetchParamsInfo() {
const { ctx, service } = this;
const { refresh = false } = ctx.query;
const data = await service.scripts.fetchParams(refresh);
ctx.success(data);
}
async fetchHelpInfo() {
const { ctx, service } = this;
const { scriptId } = ctx.params;
const data = await service.scripts.fetchHelp(scriptId);
ctx.success(data);
}
async fetchQueryButtonInfo() {
const { ctx, service } = this;
const { scriptId } = ctx.params;
const data = await service.scripts.fetchQueryButton(scriptId);
ctx.success(data);
}
async fetchNoticeInfo() {
const { ctx, service } = this;
const { scriptId } = ctx.params;
const data = await service.scripts.fetchNotice(scriptId);
ctx.success(data);
}
async fetchHubSeripts() {
const { ctx, service } = this;
let { hubId } = ctx.params;
if (hubId === 'auto') {
const ret = await service.scripts.fetchScriptIdByIp();
hubId = ret.hubId;
}
const data = await service.scripts.fetchHubSeripts(hubId);
ctx.success(data);
}
}
module.exports = ScriptController;
'use strict';
const Controller = require('egg').Controller;
class TaskController extends Controller {
constructor(ctx) {
super(ctx);
this.createRule = {
orderId: 'string',
};
this.submitRule = {
phone: {type: 'string', format: /^1\d{10}$/, required: false},
ID: {type: 'string', format: /^\d{14}(\d{3})?[\dXx]$/, required: false},
email: {type: 'email', required: false},
};
this.fetchCaptureRule = {
type: {type: 'enum', values: ['code', 'phone_code']},
};
this.taskIdRule = {
taskId: {type: 'string', format: /\d+/},
};
this.cityConfigRule = {
sign: 'string',
params: {
type: 'object',
rule: {
appKey: 'string',
timestamp: 'string',
token: 'string',
}
}
}
}
async create() {
const {ctx, service} = this;
ctx.validate(this.createRule);
const {orderId} = ctx.request.body;
const taskId = await service.task.create();
await service.order.update({orderId, taskId});
await service.cache.set({
key: taskId,
value: {status: 'init', note: {message: 'init'}},
});
ctx.success({taskId});
}
async submit() {
const {ctx, service, config} = this;
ctx.validate(this.submitRule);
const {taskId} = ctx.params;
await service.cache.set({
key: taskId,
value: {status: 'init', note: {message: 'init'}},
});
await service.task.submit({
taskId,
data: ctx.request.body,
callbackUrl: config.callbackUrl,
});
ctx.success({taskId});
}
async fetchCapture() {
const {ctx, service} = this;
ctx.validate(this.fetchCaptureRule);
const {taskId} = ctx.params;
const {type} = ctx.request.body;
const result = await service.task.fetchCapture({
taskId,
type,
});
ctx.success(result);
}
async show() {
const {ctx, service} = this;
ctx.validate(this.taskIdRule, ctx.params);
const {taskId} = ctx.params;
const data = await service.cache.get({key: taskId});
ctx.success(data);
}
async handleCallback() {
const {ctx, service} = this;
ctx.logger.info('【handleCallback】', ctx.request.body);
const {taskId} = ctx.request.body;
const result = await service.task.fetchTask({taskId});
ctx.success();
let taskNote = {
status: 'init',
note: {message: 'init'},
};
switch (result.code) {
case -1:
case 106:
case 102:
case 204:
taskNote = {
status: 'failure',
note: {message: result.msg},
};
break;
case 1:
if (result.data.data) {
result.data = {
data: JSON.parse(JSON.parse(result.data.data).post_data.strForNextStep),
loginParam: result.data.loginParam
}
}
taskNote = {
status: 'next',
note: {message: 'waiting', nextStep: result.data.loginParam},
};
break;
case 110:
taskNote = {
status: 'query',
note: {message: 'login success'},
};
break;
case 0:
taskNote = {
status: 'success',
note: {message: 'task success'},
};
try {
const order = await service.order.getOneByTaskId(taskId);
if (!order) {
throw new Error('任务已经结束了');
}
const {orderId, appkey} = order;
const script = await service.scripts.fetchOneScripts(result.data.cityId);
result.cityId = Number(result.data.cityId);
result.cityName = script.hub_name || 'unknown';
result.taskId = taskId;
result.data = JSON.parse(result.data.data);
result.orderSn = orderId;
result.orderId = orderId;
result.appKey = appkey;
delete result.code;
delete result.msg;
await service.storage.write(result);
await service.partner.notice(order);
} catch (err) {
ctx.logger.error('handleCallback', err, JSON.stringify(result));
taskNote = {
status: 'failure',
note: {message: err.message},
};
}
break;
default:
ctx.logger.warn('handleCallback', JSON.stringify(result));
break;
}
await service.cache.set({
key: taskId,
value: taskNote,
});
}
}
module.exports = TaskController;
'use strict';
const Controller = require('egg').Controller;
class TokenController extends Controller {
constructor(ctx) {
super(ctx);
this.createRule = {
sign: 'string',
params: {
type: 'object',
rule: {
appKey: 'string',
timestamp: 'string',
},
},
};
}
async create() {
const { ctx, service } = this;
ctx.validate(this.createRule);
const token = await service.signature.createToken(ctx.request.body);
ctx.success({ data: token });
}
async partnerToken(){
const { ctx, service } = this;
ctx.validate(this.createRule);
const data = await service.signature.partnerToken(ctx.request.body);
ctx.success(data);
}
}
module.exports = TokenController;
'use strict';
const REDIS_CACHE = Symbol('Context#RedisCache');
const NODE_CACHE = Symbol('Context#NodeCache');
const NodeCache = require('node-cache');
class Cache {
constructor(app) {
this.app = app;
this.name = 'unknown-cache';
}
async val(key, next, ttl) { // key存在取值,不存在存值
let data = await this.get(key);
if (data) {
return data;
}
data = await next(key);
await this.set(key, data, ttl);
return data;
}
async get(key) {
const startTime = +new Date();
const ret = await this._get(key);
let jsonText = JSON.stringify(ret);
if (jsonText === undefined) {
jsonText = 'undefined';
} else if (jsonText.length >= 128) {
if (/^\{/.test(jsonText)) {
jsonText = '{...}';
} else if (/^\[/.test(jsonText)) {
jsonText = '[...]';
} else {
jsonText = jsonText.substr(0, 125) + '...';
}
}
this.app.logger.info(`[cache](${+new Date() - startTime}ms) ${this.name}.${key}: ${jsonText}`);
// this.cacheLog(startTime, key, jsonText);
return ret;
}
async set(key, value, ttl = 60) {
return await this._set(key, value, ttl);
}
async hget(key) {
const startTime = +new Date();
let ret;
if (!this.hasOwnProperty('_hget') && this.hasOwnProperty('_get')) {
ret = await this._get(key);
return ret;
}
ret = await this._hget(key);
this.chcheLog(startTime, key, ret);
return ret;
}
async hset(key, obj, ttl = 60) {
if (!this.hasOwnProperty('_hset') && this.hasOwnProperty('_set')) {
return await this._set(key, obj, ttl);
}
return await this._hset(key, obj, ttl);
}
chcheLog(startTime, key, value) {
if (typeof value === 'object') {
value = JSON.stringify(value);
}
this.app.logger.info(`[cache](${+new Date() - startTime}ms) ${this.name}.${key}: ${value}`);
}
}
class RedisCacheWrap extends Cache {
constructor(app, redis) {
super(app);
this.redis = redis;
this.name = 'redis-cache';
}
async _get(key) {
const { redis } = this;
let value = await redis.get(key);
if (value === null) {
value = undefined;
}
if (value) {
value = JSON.parse(value);
}
return value;
}
async _set(key, value, ttl) {
const { redis } = this;
value = JSON.stringify(value);
if (ttl > 0) {
await redis.set(key, value, 'EX', ttl);
} else {
await redis.set(key, value);
}
}
async _hget(key) {
const { redis } = this;
let value = await redis.hgetall(key);
if (value === null) {
value = undefined;
}
return value;
}
async _hset(key, obj, ttl) {
const { redis } = this;
if (typeof obj !== 'object') {
obj = JSON.parse(obj);
}
if (ttl > 0) {
await redis.hmset(key, obj);
} else {
await redis.hmset(key, obj);
}
}
}
class NodeCacheWrap extends Cache {
constructor(app) {
super(app);
this.cache = new NodeCache();
this.name = 'node-cache';
}
async _get(key) {
return this.cache.get(key);
}
async _set(key, value, ttl) {
const { cache } = this;
value = JSON.parse(JSON.stringify(value));
if (ttl > 0) {
cache.set(key, value, ttl);
} else {
cache.set(key, value);
}
}
}
module.exports = {
get memcache() {
if (!this[REDIS_CACHE]) {
this[REDIS_CACHE] = new RedisCacheWrap(this, this.redis);
}
return this[REDIS_CACHE];
},
get cache() {
if (!this[NODE_CACHE]) {
this[NODE_CACHE] = new NodeCacheWrap(this);
}
return this[NODE_CACHE];
},
};
\ No newline at end of file
'use strict';
module.exports = {
success(data = false) {
const method = this.request.method.toLowerCase();
if (method === 'get') {
this.status = 200;
this.body = data || {};
} else if (method === 'post') {
this.status = 201;
this.body = data || {};
} else if (method === 'put' || method === 'delete') {
this.status = data ? 200 : 204;
this.body = data ? data : '';
} else {
this.status = 204;
this.body = '';
}
},
fail(error = '') {
this.status = 400;
this.body = {
error,
};
},
};
'use strict';
const querystring = require('querystring');
const crypto = require('crypto');
const uuid = require('uuid/v1');
function process(params) {
const keys = Object.keys(params)
.filter(key => {
return (
params[key] !== undefined &&
params[key] !== '' &&
['appSecret', 'partner_key', 'sign', 'key'].indexOf(key) < 0
);
})
.sort();
const result = {};
for (const key of keys) {
result[key] = params[key];
}
return result;
}
module.exports.buildRequestBody = function(params, needNonceStr = false) {
const { app } = this;
const { appKey, appSecret } = app.config.GJJ_OpenAPI;
params = params || {};
params.appKey = appKey;
params.timestamp = Date.now();
if (needNonceStr) {
params.nonce_str = this.genRandomStr(16);
}
const signStr = this.paramSign(appSecret, params);
return { sign: signStr, params };
};
module.exports.genRandomStr = function(length) {
return crypto.randomBytes(length).toString('hex');
};
module.exports.paramSign = function(appSecret, params) {
if (!params) {
const err = new Error('parameter params missing');
err.name = 'ParameterSignError';
throw err;
}
if (!appSecret) {
const err = new Error('parameter appSecret missing');
err.name = 'ParamSignError';
throw err;
}
const newParams = process(params);
let query = querystring.stringify(newParams);
query += '&appSecret=' + appSecret;
const signStr = crypto
.createHash('md5')
.update(query)
.digest('hex')
.toUpperCase();
return signStr;
};
module.exports.getUuid = function() {
return uuid();
};
'use strict';
module.exports = (options, app) => {
return async function errorHandler(ctx, next) {
try {
if(ctx.request.method == 'post'){
app.logger.info(JSON.stringify(ctx.request.body));
}
await next();
} catch (err) {
// 所有的异常都在 app 上触发一个 error 事件,框架会记录一条错误日志
ctx.app.emit('error', err, ctx);
const status = err.status || 500;
// 生产环境时 500 错误的详细错误内容不返回给客户端,因为可能包含敏感信息
const error = status === 500 && ctx.app.config.env === 'prod'
? 'Internal Server Error'
: err.message;
// 从 error 对象上读出各个属性,设置到响应中
ctx.fail(error);
if (status === 422) {
ctx.body.detail = err.errors;
}
ctx.status = status;
}
};
};
'use strict';
module.exports = (options, app) => {
return async function(ctx, next) {
const { request } = ctx;
const { header } = request;
// app.logger.info(header, header['x-real-ip'], header['x-forwarded-for']);
const ipStr = header['x-real-ip'] || header['x-forwarded-for'];
if (ipStr) {
request.ip = ipStr;
}
const start = new Date();
let ms = 0;
await next();
ms = new Date() - start;
app.logger.info(
`[middleware-response-time](${ms}ms) ${request.method} ${request.protocol}://${request.ip}${
request.originalUrl
} ${ctx.response.status}`
);
};
};
'use strict';
module.exports = app => {
const { DataTypes } = app.Sequelize;
const cusDatas = app.model.define('cusDatas', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
field: 'id',
},
orderId: {
type: DataTypes.STRING(255),
allowNull: false,
defaultValue: '',
primaryKey: true,
field: 'orderId',
},
appKey: {
type: DataTypes.STRING(255),
allowNull: false,
field: 'appKey',
},
type: {
type: DataTypes.STRING(255),
allowNull: true,
defaultValue: '',
field: 'type',
},
date: {
type: DataTypes.DATE,
allowNull: true,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
field: 'date',
},
text1: {
type: DataTypes.STRING(255),
allowNull: true,
defaultValue: '',
field: 'text1',
},
text2: {
type: DataTypes.STRING(255),
allowNull: true,
defaultValue: '',
field: 'text2',
},
text3: {
type: DataTypes.STRING(255),
allowNull: true,
defaultValue: '',
field: 'text3',
},
text4: {
type: DataTypes.STRING(255),
allowNull: true,
defaultValue: '',
field: 'text4',
},
date1: {
type: DataTypes.DATE,
allowNull: true,
field: 'date1',
},
date2: {
type: DataTypes.DATE,
allowNull: true,
field: 'date2',
},
},
{
tableName: 'cus_data',
timestamps: false,
});
return cusDatas;
};
\ No newline at end of file
'use strict';
module.exports = app => {
const { DataTypes } = app.Sequelize;
const taskStatsu = app.model.define('taskStatsu', {
id: {
type: DataTypes.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
field: 'id',
},
orderId: {
type: DataTypes.STRING(255),
allowNull: false,
defaultValue: '',
primaryKey: true,
field: 'orderId',
},
taskId: {
type: DataTypes.STRING(255),
allowNull: false,
defaultValue: '',
field: 'taskId',
},
userId: {
type: DataTypes.STRING(255),
allowNull: true,
defaultValue: '',
field: 'userId',
},
appkey: {
type: DataTypes.STRING(255),
allowNull: true,
field: 'appKey',
},
notifyUrl: {
type: DataTypes.STRING(500),
allowNull: true,
defaultValue: '',
field: 'notifyUrl',
},
callbackUrl: {
type: DataTypes.STRING(255),
allowNull: true,
defaultValue: '',
field: 'callbackUrl',
},
status: {
type: DataTypes.STRING(255),
allowNull: true,
defaultValue: '',
field: 'status',
},
note: {
type: DataTypes.STRING(8000),
allowNull: true,
defaultValue: '',
field: 'note',
get() {
const note = this.getDataValue('note');
if (note) {
try {
return JSON.parse(note);
} catch (error) {
return {};
}
}
return {};
},
set(val) {
this.setDataValue('note', JSON.stringify(val));
},
},
created_at: {
type: DataTypes.DATE,
allowNull: true,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
field: 'createDate',
},
updated_at: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
field: 'updateDate',
},
text1: {
type: DataTypes.STRING(255),
allowNull: true,
defaultValue: '',
field: 'text1',
},
text2: {
type: DataTypes.STRING(255),
allowNull: true,
defaultValue: '',
field: 'text2',
},
text3: {
type: DataTypes.STRING(255),
allowNull: true,
defaultValue: '',
field: 'text3',
},
}, {
tableName: 'xuexin_status',
// timestamps: false,
});
return taskStatsu;
};
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
const itRouter = router.namespace(app.config.projectRootPath);
itRouter.post('/tasks', controller.task.create); // 创建任务
itRouter.get('/tasks/:taskId', controller.task.show); // 获取任务状态
itRouter.post('/tasks/:taskId/submit', controller.task.submit); // 提交任务参数
// itRouter.post('/tasks/:taskId/capture', controller.task.fetchCapture); // 获取验证码
itRouter.post('/callback', controller.task.handleCallback); // 处理回调结果,不对外
itRouter.get('/theme/:appKey', controller.partner.show);// 配置主题
itRouter.get('/agreements/:id', controller.partner.fetchAgreements);//查询协议
itRouter.post('/tokens', controller.token.create); // 创建token
itRouter.post('/orders', controller.order.create); // 创建订单号
itRouter.post('/getToken', controller.token.partnerToken); // 合作方获取token
itRouter.post('/getorderSn', controller.order.partnerOrder); // 合作方获取orderSn
itRouter.post('/getData', controller.order.partnerData); // 合作方拉数据
itRouter.get('/orderData/:appKey/:orderId', controller.order.orderShow);//获取展示页面数据
};
\ No newline at end of file
'use strict';
module.exports = {
schedule: {
interval: '60m', // 测试60分钟间隔
type: 'all', // 所有woker
immediate: true,
},
async task(ctx) {
try {
const { host, customerUrl } = ctx.app.config.signatureAPI;
const notifyMap = new Map();
ctx.logger.info('host',host, 'customerUrl', customerUrl)
const ret = await ctx.curl(host + customerUrl, {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
contentType: 'json',
});
if (ret.data.code === 0) {
ret.data.data.customerList.map(customer => {
if ('callBackUrl' in customer) {
notifyMap.set(customer.appKey, { notifyUrl: customer.callBackUrl });
}
});
ctx.app.notifyMap = notifyMap;
}
} catch (e) {
ctx.logger.error('【schedule/notifyUrlTask】catch error:', JSON.stringify(e));
}
},
};
'use strict';
const Service = require('egg').Service;
class CacheService extends Service {
constructor(ctx) {
super(ctx);
const { config } = this;
const { taskPrefix } = config.lockKeys;
this.taskPrefix = taskPrefix;
}
/**
* 将taskId状态缓存到redis和数据库
* @param {Object} key taskId
* - value: 状态 提示信息 status 、note={}
* - exprie: 过期时间
*/
async set({ key, value = {}, exprie = 300 }) {
const { ctx, app, taskPrefix } = this;
const data = await app.redis.get(taskPrefix + key);
if (!data || (data && data.status !== 'success')) {
await app.redis.set(taskPrefix + key, JSON.stringify(value), 'EX', exprie);
}
const order = await ctx.model.TaskStatus.findOne({
where: { taskId: key },
});
if (order && order.status !== 'success') {
await order.update({ ...value });
} else {
ctx.logger.error('【Cache】set no order or already success', key);
}
ctx.logger.info(`【Cache】set ${key} value:`, JSON.stringify(value));
}
/**
* 获取task状态 优先redis
* @param {Object} key taskId
* @return {Object} status note
*/
async get({ key }) {
const { ctx, app, taskPrefix } = this;
const data = await app.redis.get(taskPrefix + key);
if (data) {
ctx.logger.info(`【Cache】get From redis ${key} data:`, data);
return JSON.parse(data);
}
const order = await ctx.model.TaskStatus.findOne({
where: { taskId: key },
});
if (order) {
ctx.logger.info(`【Cache】get From Model ${key} order:`, JSON.stringify({ status: order.status, note: order.note }));
return { status: order.status, note: order.note };
}
ctx.logger.error(`【Cache】get No Result ${key} `);
this.ctx.throw(400, { message: 'no taskId' });
}
}
module.exports = CacheService;
\ No newline at end of file
'use strict';
const Service = require('egg').Service;
class OrderService extends Service {
async getOneByOrderId(orderId) {
const { ctx } = this;
const order = await ctx.model.TaskStatus.findOne({
where: { orderId },
});
return order;
}
async getOneByTaskId(taskId) {
const { ctx } = this;
const order = await ctx.model.TaskStatus.findOne({
where: { taskId },
});
return order;
}
async create(params) {
const { ctx } = this;
const order = await ctx.model.TaskStatus.findOne({
where: { orderId: params.orderId },
});
if (order) {
ctx.throw(400, { message: 'already have order' });
}
await ctx.model.TaskStatus.create(params);
return order;
}
async update(params) {
const { ctx } = this;
const order = await ctx.model.TaskStatus.findAll({
where: { orderId: params.orderId },
order: [['createDate', 'DESC']],
});
if (order.length === 0) {
ctx.throw(400, { message: 'no order' });
return;
}
for (const item of order) {
if (item.status === 'success') {
ctx.throw(400, { message: 'orderId success' });
return;
}
}
const { appKey, taskId, notifyUrl, backUrl, userId } = order[0];
if (taskId) {
await ctx.model.TaskStatus.create({ appKey, status: 'init', notifyUrl, backUrl, userId, ...params })
} else {
await order[0].update(params);
}
return order[0];
}
}
module.exports = OrderService;
'use strict';
const Service = require('egg').Service;
class PartnerService extends Service {
constructor(ctx) {
super(ctx);
const { config: { partnerAPI } } = this;
this.partnerAPI = partnerAPI;
}
async fetchTheme(appKey) {
const { ctx, partnerAPI: { fetchTheme, host, redisThemePrefix } } = this;
if (appKey) {
const data = await this.app.redis.get(redisThemePrefix + appKey);
if (data) {
try {
return JSON.parse(data);
} catch (err) {
ctx.logger.error('【Scripts】fetchParams', redisThemePrefix + appKey, 'result:', data, err);
await this.app.redis.del(redisThemePrefix + appKey);
}
}
}
const ret = await ctx.curl(`${host + fetchTheme}`, {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
method: 'GET',
data: {
appKey,
subject: 'it'
}
});
ctx.logger.info(`【Partner】 fetchTheme ${host + fetchTheme}/${appKey}`, ret.data);
if (ret.status === 200 && ret.data && ret.data.length > 0 && ret.data[0].appKey === appKey) {
await this.app.redis.set(redisThemePrefix + appKey, JSON.stringify(ret.data[0]), 'EX', 300);
}
return ret.data[0];
}
async fetchInfo(appKey){
const { ctx, partnerAPI: { fetchInfo, host, redisInfoPrefix } } = this;
if (appKey) {
const data = await this.app.redis.get(redisInfoPrefix + appKey);
if (data) {
try {
return JSON.parse(data);
} catch (err) {
ctx.logger.error('【Scripts】fetchInfo', redisInfoPrefix + appKey, 'result:', data, err);
await this.app.redis.del(redisInfoPrefix + appKey);
}
}
}
const ret = await ctx.curl(`${host + fetchInfo}`, {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
method: 'GET',
data: {
appKey
}
});
ctx.logger.info(`【Partner】 fetchTheme ${host + fetchInfo}?appKey=${appKey}`, ret.data);
if (ret.status === 200 && ret.data && ret.data.length > 0 && ret.data[0].appKey === appKey) {
await this.app.redis.set(redisInfoPrefix + appKey, JSON.stringify(ret.data[0]), 'EX', 300);
}
return ret.data[0];
}
async fetchScripts(appKey) {
const { ctx, partnerAPI: { fetchScripts, host, redisScriptsPrefix } } = this;
if (appKey) {
const data = await this.app.redis.get(redisScriptsPrefix + appKey);
if (data) {
try {
return JSON.parse(data);
} catch (err) {
ctx.logger.error('【Partner】 fetchScripts', redisScriptsPrefix + appKey, 'result:', JSON.stringify(data), err);
await this.app.redis.del(redisScriptsPrefix + appKey);
}
}
}
const url = `${host + fetchScripts}/${appKey}`;
const ret = await ctx.curl(url, {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
method: 'GET',
});
ctx.logger.info(`【Partner】 fetchTheme ${url}`, JSON.stringify(ret.data));
if (ret.status === 200 && ret.data && ret.data.id === appKey) {
await this.app.redis.set(redisScriptsPrefix + appKey, JSON.stringify(ret.data), 'EX', 300);
}
return ret.data;
}
async fetchAgreements(id) {
const { ctx, partnerAPI: { fetchAgreements, host, redisAgreementsPrefix } } = this;
const data = await this.app.redis.get(redisAgreementsPrefix + id);
if (data) {
try {
return JSON.parse(data);
} catch (err) {
ctx.logger.error('【Partner】 fetchAgreements', redisAgreementsPrefix + id, 'result:', JSON.stringify(data), err);
await this.app.redis.del(redisAgreementsPrefix + id);
}
}
const url = `${host + fetchAgreements}/${id}`;
const ret = await ctx.curl(url, {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
method: 'GET',
});
ctx.logger.info(`【Partner】 fetchAgreements ${url}`, JSON.stringify(ret.data));
if (ret.status === 200 && ret.data && ret.data.id === id) {
await this.app.redis.set(redisScriptsPrefix + appKey, JSON.stringify(ret.data), 300);
}
return ret.data;
}
async notice(order) {
const { ctx } = this;
const { orderId, notifyUrl, userId, notice } = order;
if (notifyUrl && notice !== '1') {
const ret = await ctx.curl(notifyUrl, {
charset: 'utf-8',
timeout: ['30s', '30s'],
contentType: 'json',
method: 'POST',
data: {
orderId,
userId,
status: 'success'
},
}
);
ctx.logger.info(`【Partner】 notice ${notifyUrl}`, 'orderId:', orderId, 'result:', ret.status, JSON.stringify(ret.data));
if (ret.status == 200) {
await order.update({ notice: '1' });
}
}
return
}
}
module.exports = PartnerService;
'use strict';
const Service = require('egg').Service;
class ScriptsService extends Service {
constructor(ctx) {
super(ctx);
const { config } = this;
const { scriptsAPI } = config;
this.scriptsAPI = scriptsAPI;
this.baseURL = scriptsAPI.host;
this.fetchScriptsUrl = scriptsAPI.fetchScriptsUrl;
this.fetchOneScriptUrl = scriptsAPI.fetchOneScriptUrl;
this.fetchParamsInfoUrl = scriptsAPI.fetchParamsInfoUrl;
this.fetchHelpUrl = scriptsAPI.fetchHelpUrl;
this.redisScriptsKey = scriptsAPI.redisScriptsKey;
this.redisParamsKey = scriptsAPI.redisParamsKey;
}
async fetchScripts() {
const { baseURL, fetchScriptsUrl, redisScriptsKey, ctx } = this;
const data = await this.app.redis.get(redisScriptsKey);
if (data) {
try {
return JSON.parse(data);
} catch (err) {
ctx.logger.error('【Scripts】fetchScriptsFromRedis', 'result:', data, err);
await this.app.redis.del(redisScriptsKey);
}
}
const result = await ctx.curl(baseURL + fetchScriptsUrl, {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
contentType: 'json',
});
ctx.logger.info(`【Scripts】fetchScripts,${baseURL + fetchScriptsUrl}`);
if (result.data && result.data.length > 0) {
await this.app.redis.set(redisScriptsKey, JSON.stringify(result.data), 'EX', 300);
}
return result.data;
}
async fetchOneScripts(scriptId) {
const { baseURL, fetchOneScriptUrl, ctx } = this;
const result = await ctx.curl(baseURL + fetchOneScriptUrl + '/' + scriptId, {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
contentType: 'json',
});
return result.data;
}
async fetchParams(refresh = false) {
const { baseURL, fetchParamsInfoUrl, redisParamsKey, ctx } = this;
if (!refresh) {
const data = await this.app.redis.get(redisParamsKey);
if (data) {
try {
return JSON.parse(data);
} catch (err) {
ctx.logger.error('【Scripts】fetchParams', 'result:', data, err);
await this.app.redis.del(redisParamsKey);
}
}
}
const result = await ctx.curl(baseURL + fetchParamsInfoUrl, {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
contentType: 'json',
});
// ctx.logger.info(`【Scripts】fetchParams,${baseURL + fetchParamsInfoUrl}`, 'result:', result.data);
if (result.data && result.data.length > 0) {
await this.app.redis.set(redisParamsKey, JSON.stringify(result.data), 'EX', 3000);
}
return result.data;
}
async fetchHelp(scriptId) {
const { baseURL, scriptsAPI: { fetchHelpUrl }, ctx } = this;
const result = await ctx.curl(baseURL + fetchHelpUrl + '/' + scriptId, {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
contentType: 'json',
});
return result.data;
}
async fetchQueryButton(scriptId) {
const { baseURL, scriptsAPI: { fetchQueryButtonUrl }, ctx } = this;
const result = await ctx.curl(baseURL + fetchQueryButtonUrl + '/' + scriptId, {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
contentType: 'json',
});
return result.data;
}
async fetchNotice(scriptId) {
const { baseURL, scriptsAPI: { fetchNoticeUrl }, ctx } = this;
const result = await ctx.curl(baseURL + fetchNoticeUrl + '/' + scriptId, {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
contentType: 'json',
});
return result.data;
}
async fetchHubSeripts(hubId) {
const { baseURL, scriptsAPI: { fetchHubSeriptsUrl }, ctx } = this;
const result = await ctx.curl(baseURL + fetchHubSeriptsUrl + '/' + hubId + '/scripts', {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
contentType: 'json',
});
return result.data;
}
async fetchCityFormIp() {
const { ctx } = this;
const { ip } = ctx.request;
ctx.logger.info(ctx.request);
const url = `https://api.map.baidu.com/location/ip?ak=3TBenWOhPygtFFazaR5kSibU&ip=${ip}`;
const result = await ctx.curl(url, {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
contentType: 'json',
});
if (result.data.status === 0) {
return result.data.content.address_detail.city;
}
ctx.logger.error('fetchCityFormIp', url, ip, result.data);
return '北京市';
}
async fetchScriptByCityName(name) {
const { baseURL, scriptsAPI: { fetchScriptByCityNameUrl }, ctx } = this;
const result = await ctx.curl(baseURL + fetchScriptByCityNameUrl + '?name=' + encodeURIComponent(name), {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
contentType: 'json',
});
ctx.logger.info(`fetchScriptByCityName,${baseURL + fetchScriptByCityNameUrl + '?name=' + name}`, 'result:', result.data);
return result.data;
}
async fetchScriptIdByIp() {
const city = await this.fetchCityFormIp();
const scriptList = await this.fetchScriptByCityName(city);
return scriptList;
}
}
module.exports = ScriptsService;
\ No newline at end of file
'use strict';
const Service = require('egg').Service;
class SignatureService extends Service {
constructor(ctx) {
super(ctx);
const { config } = this;
const { signatureAPI, getDataUrl, taskAPI, lockKeys } = config;
this.baseURL = signatureAPI.host;
this.fetchTokenUrl = signatureAPI.fetchTokenUrl;
this.fetchOrderIdUrl = signatureAPI.fetchOrderIdUrl;
this.signatureUrl = signatureAPI.signatureUrl;
this.signatureType = signatureAPI.signatureType;
this.getDataUrl = getDataUrl;
this.cityConfigUrl = taskAPI.cityConfigUrl;
this.LOCK_KEY = lockKeys.fecteToken;
this.SCRIPTS_KEY = lockKeys.token;
}
_request(url, opts) {
const { ctx, baseURL } = this;
url = `${baseURL}${url}`;
opts = {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
...opts,
};
return ctx.curl(url, opts);
}
_checkSuccess(result) {
if (result.status !== 200) {
const errorMsg = result.data && result.data.error_msg ? result.data.error_msg : 'unknown error';
this.ctx.throw(result.status, errorMsg);
}
if (result.data.code !== 0) {
this.ctx.throw(400, { message: result.data.msg, code: result.data.code });
}
}
async createToken(params) {
const { fetchTokenUrl, ctx } = this;
const result = await this._request(fetchTokenUrl, {
method: 'post',
data: params,
contentType: 'json',
});
ctx.logger.info('【Signature】createToken params', JSON.stringify(params), 'result:', JSON.stringify(result.data));
this._checkSuccess(result);
return result.data.data.token;
}
async partnerToken(params){
const { fetchTokenUrl, ctx } = this;
const result = await this._request(fetchTokenUrl, {
method: 'post',
data: params,
contentType: 'json',
});
ctx.logger.info('【Signature】partnerToken params', JSON.stringify(params), 'result:', result.data);
return result.data
}
async createOrderId(params) {
const { fetchOrderIdUrl, ctx } = this;
const result = await this._request(fetchOrderIdUrl, {
method: 'post',
data: params,
contentType: 'json',
});
ctx.logger.info('【Signature】createOrderId params', JSON.stringify(params), 'result:', JSON.stringify(result.data));
this._checkSuccess(result);
return result.data.data.orderSn;
}
async partnerOrderId(params){
const { fetchOrderIdUrl, ctx } = this;
const result = await this._request(fetchOrderIdUrl, {
method: 'post',
data: params,
contentType: 'json',
});
ctx.logger.info('【Signature】partnerOrderId params', JSON.stringify(params), 'result:', result.data);
return result.data
}
async signatureCheck(params) {
const { signatureUrl, signatureType, ctx } = this;
const result = await this._request(signatureUrl, {
method: 'post',
data: { ...params, type: signatureType },
contentType: 'json',
});
ctx.logger.info('【Signature】signatureCheck params', JSON.stringify({ ...params, type: signatureType }), 'result:', JSON.stringify(result.data));
this._checkSuccess(result);
return result.data.data;
}
async cityConfig(params){
const {cityConfigUrl, ctx} = this;
const result = await this._request(cityConfigUrl,{
method: 'get',
});
return result.data
}
}
module.exports = SignatureService;
'use strict';
const Service = require('egg').Service;
class StorageService extends Service {
constructor(ctx) {
super(ctx);
const { config } = this;
const { storageAPI } = config;
this.baseURL = storageAPI.host;
this.writeUrl = storageAPI.writeUrl;
this.readUrl = storageAPI.readUrl;
this.writeType = storageAPI.writeType;
this.readDataKey = storageAPI.readDataKey;
}
_request(url, opts) {
const { ctx, baseURL } = this;
url = `${baseURL}${url}`;
opts = {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
...opts,
};
return ctx.curl(url, opts);
}
async write(data) {
const { writeUrl, writeType, ctx } = this;
const result = await this._request(writeUrl, {
method: 'post',
data: { ...data, serviceType: writeType },
contentType: 'json',
});
ctx.logger.info(`【Storage】write url:${writeUrl} params`, JSON.stringify({ ...data, serviceType: writeType }), 'result:', JSON.stringify(result.data));
if (result.data.code !== '0') {
throw new Error('存储数据出错');
}
return;
}
async read(orderId, appKey) {
const { readUrl, readDataKey, ctx } = this;
const result = await this._request(`${readUrl}/${orderId}`, {
method: 'get',
contentType: 'json',
});
ctx.logger.info(`【Storage】read url:${readUrl}/${orderId} result:`, result.data.code, result.data.msg);
if (result && result.data && result.data.code !== 0) {
ctx.logger.error(`storageAPI read ${readUrl}/${orderId}`, JSON.stringify(result.data));
ctx.throw(400, { message: result.data.msg });
}
await ctx.model.Cusdata.create({
appKey,
orderId,
type: 'xuexin'
});
return result.data.data[readDataKey];
}
}
module.exports = StorageService;
'use strict';
const Service = require('egg').Service;
class TaskService extends Service {
constructor(ctx) {
super(ctx);
const {config} = this;
const {taskAPI, LOCK_KEY} = config;
this.baseURL = taskAPI.host;
this.createTaskUrl = taskAPI.createTaskUrl;
this.submitTaskUrl = taskAPI.submitTaskUrl;
this.fetchCodeUrl = taskAPI.fetchCodeUrl;
this.fetchTaskUrl = taskAPI.fetchTaskUrl;
this.cityConfigUrl = taskAPI.cityConfigUrl;
this.LOCK_KEY = LOCK_KEY;
}
_request(url, opts) {
const {ctx, baseURL} = this;
opts = {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
contentType: 'json',
...opts,
};
ctx.logger.info('_request', `${baseURL}${url}`);
return ctx.curl(`${baseURL}${url}`, opts);
}
_checkSuccess(result) {
if (result.status !== 200) {
const errorMsg = result.data && result.data.error_msg ? result.data.error_msg : 'unknown error';
this.ctx.throw(result.status, errorMsg);
}
if (result.data.code !== 0) {
this.ctx.throw(400, {message: result.data.msg, code: result.data.code});
}
}
async create() {
const {createTaskUrl, ctx} = this;
const result = await this._request(createTaskUrl, {
method: 'post',
data: {"bankId":"10003"},
});
ctx.logger.info(`【Task】create ${createTaskUrl} result:`, JSON.stringify(result.data));
this._checkSuccess(result);
return result.data.data.taskId;
}
async fetchCapture({taskId, type}) {
const {fetchCodeUrl, ctx} = this;
const result = await this._request(fetchCodeUrl, {
method: 'post',
data: {
taskId,
type,
},
});
ctx.logger.info(`【Task】fetchCapture ${fetchCodeUrl} params`, JSON.stringify({
taskId,
type,
}), result.data.code);
this._checkSuccess(result);
return result.data.data;
}
async submit(data) {
const {submitTaskUrl, ctx} = this;
const result = await this._request(submitTaskUrl, {
method: 'post',
data,
});
ctx.logger.info(`【Task】submit ${submitTaskUrl} params`, JSON.stringify(data), JSON.stringify(result.data));
this._checkSuccess(result);
return result;
}
async fetchTask(data) {
const {fetchTaskUrl, ctx} = this;
const result = await this._request(fetchTaskUrl, {
method: 'post',
data,
});
ctx.logger.info(`【Task】fetchTask ${fetchTaskUrl} params`, JSON.stringify(data), JSON.stringify(result.data.code));
return result.data;
}
}
module.exports = TaskService;
'use strict';
const Service = require('egg').Service;
class WashDataService extends Service {
constructor(ctx) {
super(ctx);
const { config } = this;
this.washUrl = config.washAPI.host + config.washAPI.washUrl;
}
async wash(data) {
const { app, washUrl } = this;
const rawdata = this._switchData(data);
if (!washUrl) return rawdata;
const washData = await app.curl(washUrl,
{
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
data: rawdata,
method: 'post',
contentType: 'json',
});
if (washData.status !== 200) {
throw new Error('清洗数据出错');
}
if (washData.data.code !== 0) {
throw new Error('清洗数据出错');
}
return washData.data;
}
_switchData(data, appKey = '', orderId = '') {
const tmp = data.data;
const bar = {};
bar.taskId = tmp.taskId;
bar.cityId = tmp.cityId;
bar.data = JSON.parse(tmp.data);
bar.orderID = orderId;
bar.appKey = appKey;
return bar;
}
}
module.exports = WashDataService;
environment:
matrix:
- nodejs_version: '8'
install:
- ps: Install-Product node $env:nodejs_version
- npm i npminstall && node_modules\.bin\npminstall
test_script:
- node --version
- npm --version
- npm run test
build: off
'use strict';
module.exports = appInfo => {
const config = exports = {};
// use for cookie sign key, should change to your own and keep security
config.keys = appInfo.name + '_1542452126322_5141';
// add your config here
config.middleware = ['requestLog', 'errorHandler'];
// 是否启用csrf安全
config.security = {
csrf: {
enable: false,
},
domainWhiteList: [],
};
config.cors = {
origin: '*',
allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS',
credentials: true,
};
return config;
};
'use strict';
module.exports = () => {
const config = exports = {};
config.debug = true;
config.projectRootPath = '/xuexin_h5';
config.redis = {
client: {
port: 6379,
host: '116.62.55.137',
password: 'DEV8redis',
db: 0,
},
};
config.taskAPI = {
host: 'http://tm.51gjj.com:7815',
createTaskUrl: '/CreditCardServices/CreateCreditCardTask',
fetchCodeUrl: '/CreditCardServices/QueryCreditCardCode',
submitTaskUrl: '/CreditCardServices/QueryCreditCard',
fetchTaskUrl: '/CreditCardServices/GetCcData'
};
config.partnerAPI = {
host: 'https://uat-nginx.jianbing.com/zeus-api/v1',
fetchTheme: '/chaos/theme',
fetchScripts: '/chaos/partners/scripts',
fetchAgreements: '/chaos/agreements',
fetchInfo: '/chaos/partner',
redisThemePrefix: 'URANUS.XX.PARNTERS.THEME',
redisScriptsPrefix: 'URANUS.XX.PARNTERS.SCRIPTS',
redisAgreementsPrefix: 'URANUS.XX.PARNTERS.Agreements',
redisInfoPrefix: 'URANUS.XX.PARNTERS.Info',
};
config.scriptsAPI = {
host: 'https://uat-nginx.jianbing.com/zeus-api/v1',
fetchScriptsUrl: '/chaos/it/two_dimension_array/queries',
fetchOneScriptUrl: '/chaos/xx/two_dimension_array/info',
fetchParamsInfoUrl: '/chaos/xx/login_param_map',
fetchQueryButtonUrl: '/chaos/xx/query_button',
fetchHelpUrl: '/chaos/xx/help',
fetchNoticeUrl: '/chaos/xx/notice',
fetchHubSeriptsUrl: '/chaos/xx/hubs',
fetchScriptByCityNameUrl: '/chaos/xx/city_scripts',
redisScriptsKey: 'URANUS.XX.SCRIPTS',
redisParamsKey: 'URANUS.XX.PARAMS',
};
config.storageAPI = {
host: 'http://tv.51gjj.com:11252',
writeUrl: '/data',
readUrl: '/Chsi',
writeType: 'chsi',
readDataKey: 'chsiData',
};
config.washAPI = {
host: '',
washUrl: '',
};
config.signatureAPI = {
host: 'http://tj3.51gjj.com:5118',
fetchTokenUrl: '/Access/GetToken',
fetchOrderIdUrl: '/Order/GetOrderSn',
signatureUrl: '/Access/SignValidityCheck',
fetchParnterUrl: '',
signatureType: 'xx',
customerUrl: '/customer/query'
};
config.lockKeys = {
fecthHub: 'URANUS.XX.HUBS.LOCK',
fecteToken: 'URANUS.XX.TOKEN.LOCK',
token: 'URANUS.XX.TOKEN',
fecthParnters: 'URANUS.PARNTERS.LOCK',
taskPrefix: 'URANUS.TASK',
};
config.sequelize = {
datasources: [{
// 东八时区
timezone: '+08:00',
delegate: 'model',
baseDir: 'model',
dialect: 'mysql',
host: 'rm-bp1272001633qc0x9o.mysql.rds.aliyuncs.com',
database: 'data_service_dev',
username: 'hexin',
password: 'gYUHszn9#q',
port: 3306,
}],
};
config.callbackUrl = 'https://dev-nginx.jianbing.com/xuexin_h5/callback';
return config;
};
'use strict';
module.exports = () => {
const config = exports = {};
config.debug = true;
config.logger = {
dir: '/jianbing/logs/xuexin_h5',
};
config.projectRootPath = '/xuexin_h5';
config.redis = {
client: {
port: 6379,
host: process.env.REDIS_HOST,
password: process.env.REDIS_PWD,
db: 0,
},
};
config.taskAPI = {
host: 'http://tm.51gjj.com:7815',
createTaskUrl: '/CreditCardServices/CreateCreditCardTask',
fetchCodeUrl: '/CreditCardServices/QueryCreditCardCode',
submitTaskUrl: '/CreditCardServices/QueryCreditCard',
fetchTaskUrl: '/CreditCardServices/GetCcData'
};
config.partnerAPI = {
host: process.env.PARTNERAPI_HOST,
fetchTheme: '/chaos/theme',
fetchScripts: '/chaos/partners/scripts',
fetchAgreements: '/chaos/agreements',
fetchInfo: '/chaos/partner',
redisThemePrefix: 'URANUS.XX.PARNTERS.THEME',
redisScriptsPrefix: 'URANUS.XX.PARNTERS.SCRIPTS',
redisAgreementsPrefix: 'URANUS.XX.PARNTERS.Agreements',
redisInfoPrefix: 'URANUS.XX.PARNTERS.Info',
};
config.scriptsAPI = {
host: process.env.SCRIPTSAPI_HOST,
fetchScriptsUrl: '/chaos/xx/two_dimension_array/queries',
fetchOneScriptUrl: '/chaos/xx/two_dimension_array/info',
fetchParamsInfoUrl: '/chaos/xx/login_param_map',
fetchQueryButtonUrl: '/chaos/xx/query_button',
fetchHelpUrl: '/chaos/xx/help',
fetchNoticeUrl: '/chaos/xx/notice',
fetchHubSeriptsUrl: '/chaos/xx/hubs',
fetchScriptByCityNameUrl: '/chaos/xx/city_scripts',
redisScriptsKey: 'URANUS.XX.SCRIPTS',
redisParamsKey: 'URANUS.XX.PARAMS',
redisScriptListKey: 'URANUS.XX.SCRIPTLIST',
};
config.storageAPI = {
host: process.env.STORAGEAPI_HOST,
writeUrl: '/data',
readUrl: '/Chsi',
writeType: 'chsi',
readDataKey: 'chsiData',
};
config.washAPI = {
host: '',
washUrl: '',
};
config.signatureAPI = {
host: process.env.SIGNATUREAPI_HOST,
fetchTokenUrl: '/Access/GetToken',
fetchOrderIdUrl: '/Order/GetOrderSn',
signatureUrl: '/Access/SignValidityCheck',
fetchParnterUrl: '',
signatureType: 'xx',
customerUrl: '/customer/query',
};
config.lockKeys = {
fecthHub: 'URANUS.XX.HUBS.LOCK',
fecteToken: 'URANUS.XX.TOKEN.LOCK',
token: 'URANUS.XX.TOKEN',
fecthParnters: 'URANUS.PARNTERS.LOCK',
taskPrefix: 'URANUS.TASK',
};
config.sequelize = {
datasources: [{
// 东八时区
timezone: '+08:00',
delegate: 'model',
baseDir: 'model',
dialect: 'mysql',
host: process.env.MYSQL_PACHONG_HOST,
database: process.env.MYSQL_DATA_SERVER_DB_NAME,
username: process.env.MYSQL_USER,
password: process.env.MYSQL_PWD,
port: process.env.MYSQL_PORT,
}],
};
config.callbackUrl = process.env.CALLBACK_URL;
return config;
};
'use strict';
// had enabled by egg
// exports.static = true;
exports.mysql = {
enable: false,
package: 'egg-mysql',
};
exports.sequelize = {
enable: true,
package: 'egg-sequelize',
};
exports.redis = {
enable: true,
package: 'egg-redis',
};
exports.routerPlus = {
enable: true,
package: 'egg-router-plus',
};
exports.cors = {
enable: true,
package: 'egg-cors',
};
exports.validate = {
enable: true,
package: 'egg-validate',
};
{
"name": "xuexin_h5",
"version": "1.0.0",
"description": "学信H5认证服务",
"private": true,
"dependencies": {
"egg": "^2.2.1",
"egg-cors": "^2.1.1",
"egg-mysql": "^3.0.0",
"egg-redis": "^2.3.0",
"egg-router-plus": "^1.3.0",
"egg-scripts": "^2.5.0",
"egg-sequelize": "^4.2.0",
"egg-validate": "^2.0.2",
"mysql2": "^1.6.4",
"node-cache": "^4.2.0",
"node-uuid": "^1.4.8",
"uuid": "^3.3.2"
},
"devDependencies": {
"autod": "^3.0.1",
"autod-egg": "^1.0.0",
"egg-bin": "^4.3.5",
"egg-ci": "^1.8.0",
"egg-mock": "^3.14.0",
"eslint": "^4.11.0",
"eslint-config-egg": "^6.0.0",
"webstorm-disable-index": "^1.2.0"
},
"engines": {
"node": ">=8.9.0"
},
"scripts": {
"start": "egg-scripts start --daemon --title=egg-server-xuexin_h5",
"stop": "egg-scripts stop --title=egg-server-xuexin_h5",
"docker": "eggctl start --title=egg-server-xuexin_h5",
"dev": "egg-bin dev",
"debug": "egg-bin debug",
"test": "npm run lint -- --fix && npm run test-local",
"test-local": "egg-bin test",
"cov": "egg-bin cov",
"lint": "eslint .",
"ci": "npm run lint && npm run cov",
"autod": "autod"
},
"ci": {
"version": "8"
},
"repository": {
"type": "git",
"url": ""
},
"author": "HAYWAEL",
"license": "MIT"
}
'use strict';
const { app, assert } = require('egg-mock/bootstrap');
describe('test/app/controller/home.test.js', () => {
it('should assert', function* () {
const pkg = require('../../../package.json');
assert(app.config.keys.startsWith(pkg.name));
// const ctx = app.mockContext({});
// yield ctx.service.xx();
});
it('should GET /', () => {
return app.httpRequest()
.get('/')
.expect('hi, egg')
.expect(200);
});
});
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment