Browse Source

多平台请求抽象化

pull/3/head
yuan_yi 3 years ago
parent
commit
974455267e
  1. 2
      code/VideoAccess-VCMP/api/app/lib/controllers/camera/index.js
  2. 10
      code/VideoAccess-VCMP/api/app/lib/index.js
  3. 2
      code/VideoAccess-VCMP/api/app/lib/middlewares/api-log.js
  4. 1
      code/VideoAccess-VCMP/api/app/lib/middlewares/authenticator.js
  5. 50
      code/VideoAccess-VCMP/api/app/lib/middlewares/business-rest.js
  6. 21
      code/VideoAccess-VCMP/api/app/lib/middlewares/paasRequest.js
  7. 1
      code/VideoAccess-VCMP/api/app/lib/service/redis.js
  8. 45
      code/VideoAccess-VCMP/api/app/lib/service/request.js
  9. 152
      code/VideoAccess-VCMP/api/config.js

2
code/VideoAccess-VCMP/api/app/lib/controllers/camera/index.js

@ -6,6 +6,8 @@ async function get (ctx, next) {
const { limit, page, orderBy, orderDirection } = ctx.query
const { userId } = ctx.fs.api
const aa = await ctx.app.fs.axyRequest.get('structures/types', { query: { token: 'b11b7e6d-032e-4e3e-8973-931c2c5ada5a' } })
let findOption = {
attributes: { exclude: ['delete', 'recycleTime',] },
where: {

10
code/VideoAccess-VCMP/api/app/lib/index.js

@ -5,7 +5,9 @@ const redisConnect = require('./service/redis')
const socketConect = require('./service/socket')
const authenticator = require('./middlewares/authenticator');
// const apiLog = require('./middlewares/api-log');
const businessRest = require('./middlewares/business-rest');
const paasRequest = require('./middlewares/paasRequest');
module.exports.entry = function (app, router, opts) {
app.fs.logger.log('info', '[FS-AUTH]', 'Inject auth and api mv into router.');
@ -18,8 +20,12 @@ module.exports.entry = function (app, router, opts) {
redisConnect(app, opts)
socketConect(app, opts)
// 实例其他平台请求方法
paasRequest(app, opts)
router.use(authenticator(app, opts));
// router.use(businessRest(app, router, opts));
// 日志记录
// router.use(apiLog(app, opts));
router = routes(app, router, opts);

2
code/VideoAccess-VCMP/api/app/lib/middlewares/api-log.js

@ -71,7 +71,7 @@ function factory(app, opts) {
partition: 0
}];
await sendToEsAsync(producer, payloads);
// await sendToEsAsync(producer, payloads);
} catch (e) {
ctx.fs.logger.error(`日志记录失败: ${e}`);

1
code/VideoAccess-VCMP/api/app/lib/middlewares/authenticator.js

@ -94,7 +94,6 @@ let isResourceAvailable = function (resources, options) {
let authCode = null;
// authorize user by authorization attribute
const { authAttr, method, path } = options;
console.log(resources, options)
for (let prop in authAttr) {
let keys = [];
let re = pathToRegexp(prop.replace(/\:[A-Za-z_\-]+\b/g, '(\\d+)'), keys);

50
code/VideoAccess-VCMP/api/app/lib/middlewares/business-rest.js

@ -1,50 +0,0 @@
'use strict';
const request = require('superagent');
const buildUrl = (url,token) => {
let connector = url.indexOf('?') === -1 ? '?' : '&';
return `${url}${connector}token=${token}`;
};
function factory(app, router, opts) {
return async function (ctx, next) {
const token = ctx.fs.api.token;
//console.log(username,password)
const req = {
get: (url, query) => {
return request
.get(buildUrl(url,token))
.query(query)
},
post: (url, data, query) => {
return request
.post(buildUrl(url,token))
.query(query)
//.set('Content-Type', 'application/json')
.send(data);
},
put: (url, data) => {
return request
.put(buildUrl(url,token))
//.set('Content-Type', 'application/json')
.send(data);
},
delete: (url) => {
return request
.del(buildUrl(url,token))
},
};
app.business = app.business || {};
app.business.request = req;
await next();
};
}
module.exports = factory;

21
code/VideoAccess-VCMP/api/app/lib/middlewares/paasRequest.js

@ -0,0 +1,21 @@
'use strict';
const request = require('../service/request')
function factory (app, opts) {
if (opts.pssaRequest) {
try {
for (let r of opts.pssaRequest) {
if (r.name && r.root) {
app.fs[r.name] = new request(r.root)
} else {
throw 'opts.pssaRequest 参数错误!'
}
}
} catch (error) {
console.error(error)
process.exit(-1);
}
}
}
module.exports = factory;

1
code/VideoAccess-VCMP/api/app/lib/service/redis.js

@ -1,7 +1,6 @@
'use strict';
// https://github.com/luin/ioredis
const redis = require("ioredis")
const moment = require('moment')
module.exports = async function factory (app, opts) {
let client = new redis(opts.redis.port, opts.redis.host);

45
code/VideoAccess-VCMP/api/app/lib/service/request.js

@ -0,0 +1,45 @@
const request = require('superagent')
module.exports = class paasRequest {
constructor(root, ctx) {
this.root = root;
}
#buildUrl = (url) => {
return `${this.root}/${url}`;
}
#resultHandler = (resolve, reject) => {
return (err, res) => {
if (err) {
reject(err);
} else {
resolve(res.body);
}
};
}
get = (url, { query, header = {} }) => {
return new Promise((resolve, reject) => {
request.get(this.#buildUrl(url)).set(header).query(query).end(this.#resultHandler(resolve, reject));
})
}
post = (url, data, query) => {
return new Promise((resolve, reject) => {
request.post(this.#buildUrl(url, this.root)).set(header).query(query).send(data).end(this.#resultHandler(resolve, reject));
})
}
put = (url, data) => {
return new Promise((resolve, reject) => {
request.put(this.#buildUrl(url)).set(setHeader()).send(data).end(this.#resultHandler(resolve, reject));
})
}
delete = (url) => {
return new Promise((resolve, reject) => {
request.delete(this.#buildUrl(url)).set(setHeader()).end(this.#resultHandler(resolve, reject));
})
}
}

152
code/VideoAccess-VCMP/api/config.js

@ -25,91 +25,95 @@ const IOTA_REDIS_SERVER_PORT = process.env.IOTA_REDIS_SERVER_PORT || flags.redis
const IOTA_REDIS_SERVER_PWD = process.env.IOTA_REDIS_SERVER_PWD || flags.redisPswd || "";//redis 密码
if (!IOT_VIDEO_ACCESS_DB || !IOTA_REDIS_SERVER_HOST || !IOTA_REDIS_SERVER_PORT) {
console.log('缺少启动参数,异常退出');
args.showHelp();
process.exit(-1);
console.log('缺少启动参数,异常退出');
args.showHelp();
process.exit(-1);
}
const product = {
port: flags.port || 8080,
staticDirs: ['static'],
mws: [
{
entry: require('@fs/attachment').entry,
opts: {
local: {
origin: IOT_VIDEO_ACCESS_LOCAL_SVR_ORIGIN || `http://localhost:${flags.port || 8080}`,
rootPath: 'static',
childPath: 'upload',
},
maxSize: 104857600, // 100M
}
}, {
entry: require('./app').entry,
opts: {
exclude: [], // 不做认证的路由,也可以使用 exclude: ["*"] 跳过所有路由
redis: {
host: IOTA_REDIS_SERVER_HOST,
port: IOTA_REDIS_SERVER_PORT,
pwd: IOTA_REDIS_SERVER_PWD
},
}
}
],
dc: {
url: IOT_VIDEO_ACCESS_DB,
opts: {
pool: {
max: 80,
min: 10,
idle: 10000
port: flags.port || 8080,
staticDirs: ['static'],
mws: [
{
entry: require('@fs/attachment').entry,
opts: {
local: {
origin: IOT_VIDEO_ACCESS_LOCAL_SVR_ORIGIN || `http://localhost:${flags.port || 8080}`,
rootPath: 'static',
childPath: 'upload',
},
define: {
freezeTableName: true, // 固定表名
timestamps: false // 不含列 "createAt"/"updateAt"/"DeleteAt"
maxSize: 104857600, // 100M
}
}, {
entry: require('./app').entry,
opts: {
exclude: [], // 不做认证的路由,也可以使用 exclude: ["*"] 跳过所有路由
redis: {
host: IOTA_REDIS_SERVER_HOST,
port: IOTA_REDIS_SERVER_PORT,
pwd: IOTA_REDIS_SERVER_PWD
},
timezone: '+08:00',
logging: false
},
models: [require('./app').models]
},
logger: {
level: 'info',
json: false,
filename: path.join(__dirname, 'log', 'runtime.log'),
colorize: false,
maxsize: 1024 * 1024 * 5,
rotationFormat: false,
zippedArchive: true,
maxFiles: 10,
prettyPrint: true,
label: '',
timestamp: () => moment().format('YYYY-MM-DD HH:mm:ss.SSS'),
eol: os.EOL,
tailable: true,
depth: null,
showLevel: true,
maxRetries: 1
}
pssaRequest: [{ // name 会作为一个 request 出现在 ctx.app.fs
name: 'axyRequest',
root: 'http://127.0.0.1:4100'
}]
}
}
],
dc: {
url: IOT_VIDEO_ACCESS_DB,
opts: {
pool: {
max: 80,
min: 10,
idle: 10000
},
define: {
freezeTableName: true, // 固定表名
timestamps: false // 不含列 "createAt"/"updateAt"/"DeleteAt"
},
timezone: '+08:00',
logging: false
},
models: [require('./app').models]
},
logger: {
level: 'info',
json: false,
filename: path.join(__dirname, 'log', 'runtime.log'),
colorize: false,
maxsize: 1024 * 1024 * 5,
rotationFormat: false,
zippedArchive: true,
maxFiles: 10,
prettyPrint: true,
label: '',
timestamp: () => moment().format('YYYY-MM-DD HH:mm:ss.SSS'),
eol: os.EOL,
tailable: true,
depth: null,
showLevel: true,
maxRetries: 1
}
};
const development = {
port: product.port,
staticDirs: product.staticDirs,
mws: product.mws,
dc: product.dc,
logger: product.logger
port: product.port,
staticDirs: product.staticDirs,
mws: product.mws,
dc: product.dc,
logger: product.logger
};
if (dev) {
// mws
for (let mw of development.mws) {
// if (mw.opts.exclude) mw.opts.exclude = ['*']; // 使用 ['*'] 跳过所有路由
}
// logger
development.logger.filename = path.join(__dirname, 'log', 'development.log');
development.logger.level = 'debug';
development.dc.opts.logging = console.log;
// mws
for (let mw of development.mws) {
// if (mw.opts.exclude) mw.opts.exclude = ['*']; // 使用 ['*'] 跳过所有路由
}
// logger
development.logger.filename = path.join(__dirname, 'log', 'development.log');
development.logger.level = 'debug';
development.dc.opts.logging = console.log;
}
module.exports = dev ? development : product;

Loading…
Cancel
Save