Commit 91d022c5 authored by 何娜's avatar 何娜

新增学信API

parents
Pipeline #6276 failed with stage
'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
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" ]
# gjj_api
公积金API查询服务
## 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
# gjj_api_server
公积金API认证服务
## 快速入门
<!-- 在此次添加使用文档 -->
如需进一步了解,参见 [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.showRule = {
sign: 'string',
params: {
type: 'object',
rule: {
token: 'string',
orderSn: {
type: 'string',
format: /^(\w{8})-(\w{4})-(\w{4})-(\w{4})-(\w{12})$/,
message: '订单号格式错误',
},
appKey: 'string',
timestamp: 'string',
},
},
};
}
//拉取数据接口
async partnerShow() {
const {ctx, service} = this;
try {
ctx.validate(this.showRule);
const {appKey, orderSn} = ctx.request.body.params;
await service.signature.signatureCheck(ctx.request.body);
let data = await service.cache.get({key: orderSn});
ctx.logger.info('getData----', data)
let result = '任务还在执行或未输入';
if (data && data.status === 'success') {
const result = await service.storage.read(orderSn, appKey);
ctx.body = {
code: 0,
data: result
};
return;
}
ctx.body = {code: -1, msg: result};
return;
} catch (err) {
ctx.logger.error('partnerShow', err);
ctx.status = 200;
if (err.code == 'invalid_param') {
return ctx.body = {code: -1, msg: err.message || ''};
}
return ctx.body = {code: -1, msg: err.message || ''};
}
}
//创建订单号接口
async fetchOrderId() {
const {ctx, service} = this;
try {
const {appKey} = ctx.params;
// 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 orderId = ctx.helper.getUuid();
const taskId = await service.task.create();
let loginParam = await service.task.fetchLoginParam();
await service.order.create({
orderId,
taskId,
notifyUrl: ctx.app.notifyMap.get(appKey) && ctx.app.notifyMap.get(appKey).notifyUrl || '',
appkey: appKey,
status: 'init',
});
ctx.body = {
code: 0,
orderSn: orderId,
loginParam,
msg: ''
}
} catch (err) {
ctx.logger.error('fetchOrderId', err);
ctx.status = 200;
if (err.code == 'invalid_param') {
return ctx.body = {code: -1, msg: err.message || ''};
}
return ctx.body = {code: err.code || -1, msg: err.message || ''};
}
}
}
module.exports = OrderController;
'use strict';
const Controller = require('egg').Controller;
class TaskController extends Controller {
constructor(ctx) {
super(ctx);
this.createRule = {
scriptId: 'number',
orderId: 'string',
};
this.submitRule = {
orderSn: {
type: 'string',
format: /^(\w{8})-(\w{4})-(\w{4})-(\w{4})-(\w{12})$/,
message: 'orderSn格式错误',
},
params: {
type: 'object',
rule: {
userName: { type: 'string', required: false },
password: { type: 'string', required: false },
},
}
};
this.fetchCaptureRule = {
orderSn: {
type: 'string',
format: /^(\w{8})-(\w{4})-(\w{4})-(\w{4})-(\w{12})$/,
message: 'orderSn格式错误',
},
type: { type: 'enum', values: ['code', 'phone_code'] },
};
this.taskIdRule = {
taskId: { type: 'string', format: /\d+/ },
};
this.cityListRule = {
sign: 'string',
params: {
type: 'object',
rule: {
token: 'string',
appKey: 'string',
timestamp: 'string',
},
},
};
}
//创建任务接口
async create() {
const { ctx, service } = this;
ctx.validate(this.createRule);
const { scriptId } = ctx.request.body;
const taskId = await service.task.create(scriptId);
ctx.success({ taskId });
}
//提交任务接口
async submit() {
const { ctx, service, config } = this;
try {
ctx.validate(this.submitRule);
const { orderSn } = ctx.request.body;
let order = await service.cache.get({ key: orderSn });
if (order.status == 'success' || order.status == 'failure') {
return ctx.body = {
code: -1,
msg: '此任务已结束'
}
}
await service.cache.set({
key: orderSn, value: {
status: 'submit',
note: { code: 3, msg: '任务已提交', data: { data: null, loginParam: null, orderSn } },
}
});
await service.task.submit({
taskId: order.taskId,
data: ctx.request.body.params,
callbackUrl: config.callbackUrl,
});
ctx.body = {
msg: null,
code: 0,
data: {
orderSn
}
};
} catch (err) {
ctx.logger.error('submit', err);
ctx.status = 200;
if (err.code == 'invalid_param') {
return ctx.body = { code: -1, msg: err.message || '' };
}
if (/[a-zA-Z]+/.test(err.message)) {
return ctx.body = { code: err.code || -1, msg: '系统错误, 请稍后再试' };
}
return ctx.body = { code: err.code || -1, msg: err.message || '' };
}
}
//获取验证码接口
async fetchCapture() {
const { ctx, service } = this;
try {
ctx.validate(this.fetchCaptureRule);
const { type, orderSn } = ctx.request.body;
const order = await service.cache.get({ key: orderSn });
if (order.status == 'success' || order.status == 'failure') {
return ctx.body = {
code: -1,
msg: '此任务已结束'
}
}
const result = await service.task.fetchCapture({
taskId: order.taskId,
type,
});
delete result.taskId;
ctx.body = {
code: 0,
data: { ...result, orderSn }
};
} catch (err) {
ctx.logger.error('submit', err);
ctx.status = 200;
if (err.code == 'invalid_param') {
return ctx.body = { code: -1, msg: err.message || '' };
}
if (/[a-zA-Z]+/.test(err.message)) {
return ctx.body = { code: err.code || -1, msg: '系统错误, 请稍后再试' };
}
return ctx.body = { code: err.code || -1, msg: err.message || '' };
}
}
//任务回调接口
async handleCallback() {
const { ctx, service } = this;
const { taskId } = ctx.request.body;
const result = await service.task.fetchTask({ taskId });
ctx.logger.info('【handleCallback_result】', result.code);
ctx.success();
const order = await service.order.getOneByTaskId(taskId);
if (!order) {
ctx.logger.error('handleCallback', taskId, '未查询到此任务');
return
}
const { orderId, appkey } = order;
let taskNote = {
status: 'init',
note: { code: 2, msg: '任务正在执行', data: { data: null, loginParam: null, orderSn: orderId } },
};
switch (result.code) {
case -1:
case 106:
case 102:
case 204:
taskNote = {
status: 'failure',
note: { code: -1, msg: result.msg, data: { data: null, loginParam: null, orderSn: orderId } },
};
await service.cache.set({
key: orderId,
value: taskNote,
});
await service.partner.notice(order);
break;
case 1:
taskNote = {
status: 'next',
note: { code: 1, msg: null, data: { data: null, loginParam: result.loginParam, orderSn: orderId } },
};
await service.cache.set({
key: orderId,
value: taskNote,
});
await service.partner.notice(order);
break;
case 110:
taskNote = {
status: 'query',
note: { code: 110, msg: '任务提交成功', data: { data: null, loginParam: null, orderSn: orderId } },
};
break;
case 0:
taskNote = {
status: 'success',
note: { code: 0, msg: '任务成功', data: { data: null, loginParam: null, orderSn: orderId } },
};
try {
result.data = JSON.parse(result.data.data);
result.orderId = orderId;
delete result.code;
delete result.msg;
await service.storage.write(result);
await service.cache.set({
key: orderId,
value: taskNote,
});
await service.partner.notice(order);
} catch (err) {
ctx.logger.error('handleCallback', err, JSON.stringify(result));
taskNote = {
status: 'failure',
note: { code: -1, msg: '系统错误', data: { data: null, loginParam: null, orderSn: order.orderId } },
};
}
break;
default:
ctx.logger.warn('handleCallback', JSON.stringify(result));
break;
}
}
}
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',
},
},
};
}
//获取token
async partnerCreate() {
const { ctx, service } = this;
try {
ctx.validate(this.createRule);
const token = await service.signature.createToken(ctx.request.body);
return ctx.body = {
code: 0,
data: { token },
msg: ''
}
} catch (err) {
ctx.logger.error('partnerCreate', err);
ctx.status = 200;
if (err.code == 'invalid_param') {
return ctx.body = { code: -1, msg: err.message || '' };
}
return ctx.body = { code: err.code || -1, msg: err.message || '' };
}
}
}
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();
};
\ No newline at end of file
'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;
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: false,
field: 'appKey',
},
notifyUrl: {
type: DataTypes.STRING(500),
allowNull: true,
defaultValue: '',
field: 'notifyUrl',
},
callbackUrl: {
type: DataTypes.STRING(255),
allowNull: false,
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',
},
notice: {
type: DataTypes.STRING(2),
allowNull: true,
defaultValue: '',
field: 'notice',
},
}, {
tableName: 'xuexin_status',
// timestamps: false,
});
return taskStatsu;
};
'use strict';
/**
* @param {Egg.Application} app - egg application
*/
module.exports = app => {
const { router, controller } = app;
const chsiRouter = router.namespace(app.config.projectRootPath);
chsiRouter.get('/getorderSn/:appKey', controller.order.fetchOrderId);// 合作方获取订单号
// taxRouter.post('/getCode', controller.task.fetchCapture);// 获取验证码
chsiRouter.post('/query', controller.task.submit);// 提交任务查询参数
chsiRouter.post('/getToken', controller.token.partnerCreate);// 合作方创建token
chsiRouter.post('/getData', controller.order.partnerShow);// 合作方获取订单数据
chsiRouter.post('/callback', controller.task.handleCallback); // 处理回调结果,不对外
};
'use strict';
module.exports = {
schedule: {
interval: '3m', // 5分钟间隔
type: 'all', // 所有woker
immediate: true,
},
async task(ctx) {
try {
const { host, customerUrl } = ctx.app.config.signatureAPI;
const notifyMap = new Map();
const ret = await ctx.curl(host + customerUrl, {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
contentType: 'json'
});
ctx.logger.info('notifyUrlCode', JSON.stringify(ret.data.code));
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));
}
}
};
\ No newline at end of file
'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;
}
/**
* 将orderId状态缓存到redis和数据库
* @param {Object} key orderId
* - 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: { orderId: 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));
}
/**
* 获取orderSn状态 优先redis
* @param {Object} key orderSn
* @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: { orderId: key },
});
if (order) {
ctx.logger.info(`【Cache】get From Model ${key} order:`, JSON.stringify({ status: order.status, note: order.note }));
return order;
}
ctx.logger.error(`【Cache】get No Result ${key} `);
this.ctx.throw(400, { message: '无此订单号' });
}
}
module.exports = CacheService;
'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;
await ctx.model.TaskStatus.create(params);
return;
}
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 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 notice(order) {
const { ctx } = this;
const { orderId, notifyUrl, notice } = order;
if (notifyUrl && notice !== '1') {
const ret = await ctx.curl(notifyUrl, {
charset: 'utf-8',
timeout: ['30s', '30s'],
contentType: 'json',
method: 'POST',
data: {
orderSn: orderId
},
}
)
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, cityListAPI } = config;
this.cityListAPI = cityListAPI;
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;
this.redisScriptListKey = scriptsAPI.redisScriptListKey;
}
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}`, 'result:', result.data);
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, redisScriptListKey, ctx } = this;
const data = await this.app.redis.get(redisScriptListKey + scriptId);
if (data) {
try {
return JSON.parse(data);
} catch (err) {
ctx.logger.error('【Scripts】fetchOneScriptsFromRedis', 'result:', data, err);
await this.app.redis.del(redisScriptListKey + scriptId);
}
}
const result = await ctx.curl(baseURL + fetchOneScriptUrl + '/' + scriptId, {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
contentType: 'json',
});
if (result.data && (String(result.data.id) === scriptId)) {
await this.app.redis.set(redisScriptListKey + scriptId, JSON.stringify(result.data), 'EX', 60);
}
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', 300);
}
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, JSON.stringify(result.data));
return '北京市';
}
async fetchScriptByCityName(name) {
const { baseURL, scriptsAPI: { fetchScriptByCityNameUrl }, ctx } = this;
const result = await ctx.curl(baseURL + fetchScriptByCityNameUrl + '?name=' + encodeURIComponent(name) + '&type=query', {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
contentType: 'json',
});
ctx.logger.info(`fetchScriptByCityName,${baseURL + fetchScriptByCityNameUrl + '?name=' + name}`, 'result:', JSON.stringify(result.data));
return result.data;
}
async fetchScriptIdByIp() {
const city = await this.fetchCityFormIp();
const scriptList = await this.fetchScriptByCityName(city);
return scriptList;
}
async fetchScriptName(scriptId) {
try {
const city = await this.fetchOneScripts(scriptId);
return city.name || '未知';
} catch (err) {
return '未知';
}
}
async fetchScriptList() {
const { cityListAPI, ctx } = this;
const result = await ctx.curl(cityListAPI, {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
contentType: 'json',
});
ctx.logger.info(`fetchScriptList,${cityListAPI}`, 'result:', JSON.stringify(result.data));
return result.data;
}
}
module.exports = ScriptsService;
'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);
this._checkSuccess(result);
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;
}
}
module.exports = SignatureService;
\ No newline at end of file
'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} write result:`, JSON.stringify(result.data));
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: 'gjj'
})
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.loginParamUrl = taskAPI.loginParamUrl;
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 fetchLoginParam() {
const {loginParamUrl, ctx} = this;
const result = await this._request(loginParamUrl);
ctx.logger.info(`【Task】create ${loginParamUrl} result:`, JSON.stringify(result.data.code));
this._checkSuccess(result);
let loginParam;
for(let item of result.data.bankList){
if(item.id === 10003){
loginParam = item.queryParam[0].loginParam;
}
}
return loginParam;
}
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;
\ No newline at end of file
'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;
\ No newline at end of file
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_api';
config.redis = {
client: {
port: 6379,
host: '116.62.55.137',
password: 'DEV8redis',
db: 0,
},
};
config.taskAPI = {
host: 'http://tm.51gjj.com:7815',
loginParamUrl: '/CreditCardServices/GetCcSetting',
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: 'ChsiReport',
};
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_api/callback';
return config;
};
\ No newline at end of file
'use strict';
module.exports = () => {
const config = exports = {};
config.debug = true;
config.logger = {
dir: '/jianbing/logs/xuexin_h5',
};
config.projectRootPath = '/xuexin_api';
config.redis = {
client: {
port: 6379,
host: process.env.REDIS_HOST,
password: process.env.REDIS_PWD,
db: 0,
},
};
config.taskAPI = {
host: process.env.TASKAPI_HOST,
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: 'ChsiReport',
};
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;
};
\ No newline at end of file
'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_api",
"version": "1.0.0",
"description": "个税API认证服务",
"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-gjj_api_server",
"stop": "egg-scripts stop --title=egg-server-gjj_api_server",
"docker": "eggctl start --title=egg-server-gjj_api_serverr",
"dev": "egg-bin dev --port 7002",
"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": "jd",
"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