Commit 03f367ef authored by 何娜's avatar 何娜

fix

parent 4eb9bc1f
Pipeline #4724 passed with stage
in 45 seconds
...@@ -82,15 +82,18 @@ class OrderController extends Controller { ...@@ -82,15 +82,18 @@ class OrderController extends Controller {
ctx.validate(this.fetchRule); ctx.validate(this.fetchRule);
const { appKey } = ctx.request.body.signParams.params; const { appKey } = ctx.request.body.signParams.params;
const { cityId } = ctx.request.body; const { cityId } = ctx.request.body;
const channelType = await ctx.app.redis.get(cityId);
ctx.app.redis.set(cityId, channelType, "EX", 3600);
const orderId = await service.signature.createOrderId(ctx.request.body.signParams); const orderId = await service.signature.createOrderId(ctx.request.body.signParams);
const taskId = await service.task.create(cityId); const taskId = await service.task.create({cityId, channelType});
await service.order.create({ await service.order.create({
orderId, orderId,
taskId, taskId,
cityId: cityId, cityId,
notifyUrl: ctx.app.notifyMap.get(appKey) && ctx.app.notifyMap.get(appKey).notifyUrl || '', // notifyUrl: ctx.app.notifyMap.get(appKey) && ctx.app.notifyMap.get(appKey).notifyUrl || '',
appKey: appKey, appkey: appKey,
status: 'init', status: 'init',
text1: channelType,
}); });
ctx.body = { ctx.body = {
code: 0, code: 0,
...@@ -105,9 +108,6 @@ class OrderController extends Controller { ...@@ -105,9 +108,6 @@ class OrderController extends Controller {
if (err.code == 'invalid_param') { if (err.code == 'invalid_param') {
return ctx.body = { code: -1, msg: err.message || '' }; 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 || '' }; return ctx.body = { code: err.code || -1, msg: err.message || '' };
} }
} }
......
'use strict'; 'use strict';
const REDIS_CACHE = Symbol('Context#RedisCache');
const NODE_CACHE = Symbol('Context#NodeCache'); const NODE_CACHE = Symbol('Context#NodeCache');
const NodeCache = require('node-cache'); const NodeCache = require('node-cache');
class Cache { class Cache {
constructor(app) { constructor(app) {
this.app = app; this.app = app;
this.name = 'unknown-cache'; 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 val(key, next, ttl) { async get(key) {
let data = await this.get(key); const startTime = +new Date();
if (data) { const ret = await this._get(key);
return data; 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);
} }
data = await next(key);
await this.set(key, data, ttl);
return data;
}
async get(key) { async hget(key) {
const startTime = +new Date(); const startTime = +new Date();
const ret = await this._get(key); let ret;
let jsonText = JSON.stringify(ret); if (!this.hasOwnProperty('_hget') && this.hasOwnProperty('_get')) {
if (jsonText === undefined) { ret = await this._get(key);
jsonText = 'undefined'; return ret;
} else if (jsonText.length >= 128) { }
if (/^\{/.test(jsonText)) { ret = await this._hget(key);
jsonText = '{...}'; this.chcheLog(startTime, key, ret);
} else if (/^\[/.test(jsonText)) { return ret;
jsonText = '[...]'; }
} else {
jsonText = jsonText.substr(0, 125) + '...'; 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}`);
} }
this.app.logger.info(`[cache] get (${+new Date() - startTime}ms) ${this.name}.${key}: ${jsonText}`);
return ret;
}
async set(key, value, ttl = 60) {
this.app.logger.info(`[cache] set (ms)${this.name}.${key}: ${value}`);
return await this._set(key, value, ttl);
}
async del(key){
return await this._del(key)
}
} }
class NodeCacheWrap extends Cache { class RedisCacheWrap extends Cache {
constructor(app) { constructor(app, redis) {
super(app); super(app);
this.cache = new NodeCache(); this.redis = redis;
this.name = 'node-cache'; this.name = 'redis-cache';
} }
async _get(key) { async _get(key) {
return this.cache.get(key); const { redis } = this;
} let value = await redis.get(key);
async _set(key, value, ttl) { if (value === null) {
const { cache } = this; value = undefined;
value = JSON.parse(JSON.stringify(value)); }
if (ttl > 0) { if (value) {
cache.set(key, value, ttl); value = JSON.parse(value);
} else { }
cache.set(key, 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);
}
} }
}
async _del(key){
const { cache } = this;
cache.del(key);
}
} }
module.exports = { class NodeCacheWrap extends Cache {
get cache() { constructor(app) {
if (!this[NODE_CACHE]) { super(app);
this[NODE_CACHE] = new NodeCacheWrap(this); this.cache = new NodeCache();
this.name = 'node-cache';
} }
return this[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
...@@ -110,7 +110,7 @@ module.exports = app => { ...@@ -110,7 +110,7 @@ module.exports = app => {
field: 'text3', field: 'text3',
}, },
}, { }, {
tableName: 'taxh5_status', tableName: 'tax_status',
// timestamps: false, // timestamps: false,
}); });
......
...@@ -10,10 +10,10 @@ module.exports = app => { ...@@ -10,10 +10,10 @@ module.exports = app => {
taxRouter.post('/getToken', controller.token.partnerCreate);// 合作方创建token taxRouter.post('/getToken', controller.token.partnerCreate);// 合作方创建token
taxRouter.post('/getorderSn', controller.order.fetchOrderId);// 合作方获取订单号
taxRouter.get('/getCity', controller.task.cityConfigs);// 获取城市基础配置项 taxRouter.get('/getCity', controller.task.cityConfigs);// 获取城市基础配置项
taxRouter.post('/getorderSn', controller.order.fetchOrderId);// 合作方获取订单号
taxRouter.post('/getCode', controller.task.fetchCapture);// 获取验证码 taxRouter.post('/getCode', controller.task.fetchCapture);// 获取验证码
taxRouter.post('/query', controller.task.submit);// 提交任务查询参数 taxRouter.post('/query', controller.task.submit);// 提交任务查询参数
...@@ -22,5 +22,5 @@ module.exports = app => { ...@@ -22,5 +22,5 @@ module.exports = app => {
taxRouter.post('/callback', controller.task.handleCallback); // 处理回调结果,不对外 taxRouter.post('/callback', controller.task.handleCallback); // 处理回调结果,不对外
taxRouter.get('/helpInfo', controller.task.fetchCapture);// 获取帮助信息 // taxRouter.get('/helpInfo', controller.task.help);// 获取帮助信息
}; };
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
module.exports = { module.exports = {
schedule: { schedule: {
interval: '5m', // 5分钟间隔 interval: '3m', // 5分钟间隔
type: 'all', // 所有woker type: 'all', // 所有woker
immediate: true, immediate: true,
}, },
...@@ -11,14 +11,16 @@ module.exports = { ...@@ -11,14 +11,16 @@ module.exports = {
try { try {
const { host, customerUrl } = ctx.app.config.signatureAPI; const { host, customerUrl } = ctx.app.config.signatureAPI;
const notifyMap = new Map(); const notifyMap = new Map();
ctx.logger.info('host',host, 'customerUrl', customerUrl)
const ret = await ctx.curl(host + customerUrl, { const ret = await ctx.curl(host + customerUrl, {
charset: 'utf-8', charset: 'utf-8',
timeout: ['30s', '30s'], timeout: ['30s', '30s'],
dataType: 'json', dataType: 'json',
contentType: 'json', contentType: 'json',
gzip: true
}); });
// ctx.logger.info(JSON.stringify(ret.data)); ctx.logger.info('notifyUrlCode', JSON.stringify(ret.data.code));
if (ret.data.code == '0') { if (ret.data.code === '0') {
ret.data.data.customerList.map(customer => { ret.data.data.customerList.map(customer => {
if ('callBackUrl' in customer) { if ('callBackUrl' in customer) {
notifyMap.set(customer.appKey, { notifyUrl: customer.callBackUrl }); notifyMap.set(customer.appKey, { notifyUrl: customer.callBackUrl });
...@@ -30,4 +32,4 @@ module.exports = { ...@@ -30,4 +32,4 @@ module.exports = {
ctx.logger.error('【schedule/notifyUrlTask】catch error:', JSON.stringify(e)); ctx.logger.error('【schedule/notifyUrlTask】catch error:', JSON.stringify(e));
} }
} }
} };
\ No newline at end of file \ No newline at end of file
...@@ -27,7 +27,7 @@ class SignatureService extends Service { ...@@ -27,7 +27,7 @@ class SignatureService extends Service {
dataType: 'json', dataType: 'json',
...opts, ...opts,
}; };
ctx.logger.info('signnature', url, opts); // ctx.logger.info('signnature', url, opts);
return ctx.curl(url, opts); return ctx.curl(url, opts);
} }
......
...@@ -3,149 +3,139 @@ ...@@ -3,149 +3,139 @@
const Service = require('egg').Service; const Service = require('egg').Service;
class TaskService extends Service { class TaskService extends Service {
constructor(ctx) { constructor(ctx) {
super(ctx); super(ctx);
const {config} = this; const {config} = this;
const {taskAPI, LOCK_KEY} = config; const {taskAPI, LOCK_KEY} = config;
this.baseURL = taskAPI.host; this.baseURL = taskAPI.host;
this.newbaseURL = taskAPI.newhost; this.newbaseURL = taskAPI.newhost;
this.createTaskUrl = taskAPI.createTaskUrl; this.createTaskUrl = taskAPI.createTaskUrl;
this.submitTaskUrl = taskAPI.submitTaskUrl; this.submitTaskUrl = taskAPI.submitTaskUrl;
this.fetchCodeUrl = taskAPI.fetchCodeUrl; this.fetchCodeUrl = taskAPI.fetchCodeUrl;
this.fetchTaskUrl = taskAPI.fetchTaskUrl; this.fetchTaskUrl = taskAPI.fetchTaskUrl;
this.cityConfigUrl = taskAPI.cityConfigUrl; this.cityConfigUrl = taskAPI.cityConfigUrl;
this.LOCK_KEY = LOCK_KEY; this.LOCK_KEY = LOCK_KEY;
} }
_request(url, type, opts) {
const {ctx, baseURL, newbaseURL} = this;
url = (type === 'gsgj') ? `${newbaseURL}${url}` : `${baseURL}${url}`;
opts = {
charset: 'utf-8',
timeout: ['30s', '30s'],
dataType: 'json',
contentType: 'json',
...opts,
};
ctx.logger.info('_request', url, type);
return ctx.curl(url, opts);
}
_checkSuccess(result) { _request(url, type, opts) {
if (result.status !== 200) { const {ctx, baseURL, newbaseURL} = this;
const errorMsg = result.data && result.data.error_msg ? result.data.error_msg : 'unknown error'; url = (type === 'gsgj') ? `${newbaseURL}${url}` : `${baseURL}${url}`;
this.ctx.throw(result.status, errorMsg); opts = {
} charset: 'utf-8',
if (result.data.code !== 0) { timeout: ['30s', '30s'],
this.ctx.throw(400, {message: result.data.msg, code: result.data.code}); dataType: 'json',
contentType: 'json',
...opts,
};
ctx.logger.info('_request', url, type);
return ctx.curl(url, opts);
} }
}
async create(data) { _checkSuccess(result) {
const {createTaskUrl, ctx} = this; if (result.status !== 200) {
const result = await this._request(createTaskUrl, ctx.app.channelType, { const errorMsg = result.data && result.data.error_msg ? result.data.error_msg : 'unknown error';
method: 'post', this.ctx.throw(result.status, errorMsg);
data: {cityId: data}, }
}); if (result.data.code !== 0) {
ctx.logger.info(`【Task】create ${createTaskUrl} cityId: ${data} result:`, JSON.stringify(result.data)); this.ctx.throw(400, {message: result.data.msg, code: result.data.code});
ctx.logger.info('channelType', ctx.app.channelType); }
this._checkSuccess(result); }
return result.data.data.taskId;
}
async fetchCapture({taskId, type}) { async create({cityId, channelType}) {
const {fetchCodeUrl, ctx} = this; const {createTaskUrl, ctx} = this;
let channelType = taskId.length > 20 ? 'gsgj' : '51gs'; const result = await this._request(createTaskUrl, channelType, {
const result = await this._request(fetchCodeUrl, channelType, { method: 'post',
method: 'post', data: {cityId},
data: { });
taskId, ctx.logger.info(`【Task】create ${createTaskUrl} cityId: ${cityId} channelType: ${channelType} result:`, JSON.stringify(result.data));
type, this._checkSuccess(result);
}, return result.data.data.taskId;
}); }
ctx.logger.info(`【Task】fetchCapture ${fetchCodeUrl} params`, JSON.stringify({
taskId,
type,
}), result.data.code);
this._checkSuccess(result);
return result.data.data;
}
async submit(data) { async fetchCapture({taskId, type}) {
const {submitTaskUrl, ctx} = this; const {fetchCodeUrl, ctx} = this;
let channelType = data.taskId.length > 20 ? 'gsgj' : '51gs'; let channelType = taskId.length > 20 ? 'gsgj' : '51gs';
const result = await this._request(submitTaskUrl, channelType, { const result = await this._request(fetchCodeUrl, channelType, {
method: 'post', method: 'post',
data, data: {
}); taskId,
ctx.logger.info(`【Task】submit ${submitTaskUrl} params`, JSON.stringify(data), JSON.stringify(result.data)); type,
this._checkSuccess(result); },
return result; });
} ctx.logger.info(`【Task】fetchCapture ${fetchCodeUrl} params`, JSON.stringify({
taskId,
type,
}), result.data.code);
this._checkSuccess(result);
return result.data.data;
}
async fetchTask(data) { async submit(data) {
const {fetchTaskUrl, ctx} = this; const {submitTaskUrl, ctx} = this;
let channelType = data.taskId.length > 20 ? 'gsgj' : '51gs'; let channelType = data.taskId.length > 20 ? 'gsgj' : '51gs';
const result = await this._request(fetchTaskUrl, channelType, { const result = await this._request(submitTaskUrl, channelType, {
method: 'post', method: 'post',
data, data,
}); });
ctx.logger.info(`【Task】fetchTask ${fetchTaskUrl} params`, JSON.stringify(data), JSON.stringify(result.data)); ctx.logger.info(`【Task】submit ${submitTaskUrl} params`, JSON.stringify(data), JSON.stringify(result.data));
return result.data; this._checkSuccess(result);
} return result;
}
async getCityList() { async fetchTask(data) {
const {cityConfigUrl, ctx} = this; const {fetchTaskUrl, ctx} = this;
let cityLists = [];//对外城市列表 let channelType = data.taskId.length > 20 ? 'gsgj' : '51gs';
let cityTypeLists = [];//不对外城市列表,含渠道(51/管家) const result = await this._request(fetchTaskUrl, channelType, {
let newCityMap = new Map(); method: 'post',
data,
});
ctx.logger.info(`【Task】fetchTask ${fetchTaskUrl} params`, JSON.stringify(data), JSON.stringify(result.data));
return result.data;
}
const newret = await this._request(cityConfigUrl, 'gsgj', {method: 'get'}); async getCityList() {
ctx.logger.info(`【Task】getCityList params gsgj`, newret.status, newret.data.data.length); const {cityConfigUrl, ctx} = this;
this._checkSuccess(newret); let cityLists = [];//对外城市列表
newret.data.data.map(Prov => { let newCityMap = new Map();
Prov.citys.map(city => {
newCityMap.set(String(city.id), city)
})
});
const ret = await this._request(cityConfigUrl, '51gs', {method: 'get'}); const newret = await this._request(cityConfigUrl, 'gsgj', {method: 'get'});
ctx.logger.info(`【Task】getCityList params 51gs`, ret.status, ret.data.data.length); ctx.logger.info(`【Task】getCityList params gsgj`, newret.status, newret.data.data.length);
this._checkSuccess(ret); this._checkSuccess(newret);
ret.data.data.map(Prov => { newret.data.data.map(Prov => {
let newProv = {provinceName: Prov.provinceName, citys: []}; Prov.citys.map(city => {
Prov.citys.map(city => { newCityMap.set(String(city.id), city)
city.type = "51gs"; })
if (city.state === -1 && newCityMap.get(String(city.id)) && newCityMap.get(String(city.id)).state === 1) {
city = newCityMap.get(String(city.id));
city.type = "gsgj";
ctx.logger.info('city', city)
}
if (city.state != 1) {
city.state = -1;
}
newProv.citys.push({
province: city.province,
name: city.name,
id: city.id,
state: city.state,
queryParam: city.queryParam
}); });
cityTypeLists.push({
province: city.province, const ret = await this._request(cityConfigUrl, '51gs', {method: 'get'});
name: city.name, ctx.logger.info(`【Task】getCityList params 51gs`, ret.status, ret.data.data.length);
id: city.id, this._checkSuccess(ret);
state: city.state, ret.data.data.map(Prov => {
type: city.type, let newProv = {provinceName: Prov.provinceName, citys: []};
Prov.citys.map(city => {
city.type = "51gs";
if (city.state === -1 && newCityMap.get(String(city.id)) && newCityMap.get(String(city.id)).state === 1) {
city = newCityMap.get(String(city.id));
city.type = "gsgj";
ctx.logger.info('city', city)
}
if (city.state != 1) {
city.state = -1;
}
newProv.citys.push({
province: city.province,
name: city.name,
id: city.id,
state: city.state,
queryParam: city.queryParam
});
ctx.app.redis.set(city.id, city.type, "EX", 3600)
});
cityLists.push(newProv);
}); });
}); return cityLists;
cityLists.push(newProv); }
});
ctx.app.cityTypeLists = cityTypeLists;
// ctx.logger.info('-------------', JSON.stringify(ctx.app.cityTypeLists))
return cityLists;
}
} }
module.exports = TaskService; module.exports = TaskService;
\ No newline at end of file
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