This commit is contained in:
robin
2022-07-07 22:16:39 +08:00
parent 264ab8d979
commit a9a4bd0981
86 changed files with 1198 additions and 310 deletions
+47
View File
@@ -0,0 +1,47 @@
//更多配置:http://axios-js.com/zh-cn/docs/index.html#%E8%AF%B7%E6%B1%82%E9%85%8D%E7%BD%AE
module.exports = {
// `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
// 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
baseURL: 'https://some-domain.com/api/',
// `headers` 是即将被发送的自定义请求头
headers: {'X-Requested-With': 'XMLHttpRequest'},
// `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
// 如果请求话费了超过 `timeout` 的时间,请求将被中断
timeout: 30 * 1000,
// `withCredentials` 表示跨域请求时是否需要使用凭证
withCredentials: false, // default
// `responseType` 表示服务器响应的数据类型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
responseType: 'json', // default
// `responseEncoding` indicates encoding to use for decoding responses
// Note: Ignored for `responseType` of 'stream' or client-side requests
responseEncoding: 'utf8', // default
// `xsrfCookieName` 是用作 xsrf token 的值的cookie的名称
xsrfCookieName: 'XSRF-TOKEN', // default
// `xsrfHeaderName` is the name of the http header that carries the xsrf token value
xsrfHeaderName: 'X-XSRF-TOKEN', // default
// `maxContentLength` 定义允许的响应内容的最大尺寸
// maxContentLength: 2000,
// `maxRedirects` 定义在 node.js 中 follow 的最大重定向数目
// 如果设置为0,将不会 follow 任何重定向
// maxRedirects: 5, // default
// 'proxy' 定义代理服务器的主机名称和端口
// `auth` 表示 HTTP 基础验证应当用于连接代理,并提供凭据
// 这将会设置一个 `Proxy-Authorization` 头,覆写掉已有的通过使用 `header` 设置的自定义 `Proxy-Authorization` 头。
// proxy: {
// host: '127.0.0.1',
// port: 9000,
// auth: {
// username: 'mikeymike',
// password: 'rapunz3l'
// }
// },
}
+16
View File
@@ -0,0 +1,16 @@
/**
* Axios 是一个基于 promise 的 HTTP 库
*/
const config = require("./config")
const axios = require('axios');
const request = require('./request');
const requestError = require('./request.error');
const response = require('./response');
const responseError = require('./response.error');
module.exports = async (app) => {
Object.assign(axios.defaults, config)
axios.interceptors.request.use(request,requestError)
axios.interceptors.response.use(response,responseError)
app.axios = axios
app.alias["$axios"] = app.axios
}
+6
View File
@@ -0,0 +1,6 @@
//请求拦截器错误时
module.exports = (error) => {
// 对请求错误做些什么
return Promise.reject(error);
}
+5
View File
@@ -0,0 +1,5 @@
//请求拦截器
module.exports = (config) => {
// 在发送请求之前做些什么
return config;
}
+6
View File
@@ -0,0 +1,6 @@
//响应拦截器错误时
module.exports = (error) => {
// 对请求错误做些什么
return Promise.reject(error);
}
+5
View File
@@ -0,0 +1,5 @@
//响应拦截器
module.exports = (response) => {
// 对响应数据做点什么
return response;
}
+2 -2
View File
@@ -1,14 +1,14 @@
module.exports = {
success: (body, msg, status) => {
return {
res : body || null,
data : body || null,
status: status || 200,
message : msg || "success"
}
},
error : (body, msg, status) => {
return {
res : body || null,
data : body || null,
status: status || 400,
message : msg || "error"
}
+1
View File
@@ -6,4 +6,5 @@ const body = require("./body")
module.exports = async (app) => {
app.res = body
app.alias["$res"] = app.res
}
+1 -1
View File
@@ -10,7 +10,7 @@ const config = require("./config")
const mq = require("./queue")
module.exports = async (app) => {
app.mq = mq
app.alias["$mq"] = app.mq
const queueName = "boobam_schedule"
const queue = mq.Queue(queueName);
+4
View File
@@ -0,0 +1,4 @@
module.exports = {
path : "components/*/*.js",
app_path: "app/*/components/*/*.js",
}
+21
View File
@@ -0,0 +1,21 @@
/**
* 通用组件
* 加载components文件夹下的函数
*/
const config = require("./config")
module.exports = async (app) => {
const list = await app.load(config.path)
Object.assign(list, await app.load(config.app_path))
app.components = {}
list.forEach(item => {
if (!app.components[item.parse.file_father]) {
app.components[item.parse.file_father] = {}
}
if (item.parse.name==='index') {
Object.assign(app.components[item.parse.file_father],item.res)
}else {
app.components[item.parse.file_father][item.parse.name] = item.res
}
})
app.alias["$components"] = app.components
}
+1
View File
@@ -6,6 +6,7 @@ const config = require("./config")
const EventEmitter = require('events');
module.exports = async (app) => {
app.event = new EventEmitter()
app.alias["$event"] = app.event
const list = await app.load(config.path)
list.forEach(item => {
Object.keys(item.res).forEach(key => {
+2 -1
View File
@@ -1,3 +1,4 @@
module.exports = {
path:"middleware/*/index.js"
path:"middleware/*/index.js",
app_path: "app/*/middleware/*/index.js",
}
+9 -3
View File
@@ -2,19 +2,25 @@
* 加载中间件
* 加载app/middleware文件夹下的中间件
*/
const config = require("./config")
module.exports = async (app) => {
let list = await app.load(config.path)
let list2 = await app.load(config.app_path)
list=[...list,...list2]
// Object.assign(list, list2)
list = app.xe.orderBy(list, "res.sort")
list = list.filter(item => item.res.use)
list.forEach(async item => {
console.log('加载的中间件:',item.parse.dir);
if (item.res.loadFun) {
//如果中间件定义了特殊加载方法
await item.res.loadFun(app, item.res.fun)
} else {
app.use(async (ctx, next) => {
return await item.res.fun(ctx, next, app)
})
app.use(async (ctx, next) => {
return await item.res.fun(ctx, next, app)
})
}
})
+49 -49
View File
@@ -2,22 +2,22 @@
const Sequelize = require("sequelize");
const xe = require("xe-utils")
module.exports = class Api {
constructor(sequelize,models) {
constructor(sequelize, models) {
this.sequelize = sequelize
this.models = models
this.init()
}
init() {
this.tableName = ""
this.tableWhere = ""
this.tableData = ""
this.tablePage = ""
this.tableLimit = ""
this.tableOrder = ""
this.tableGroup = ""
this.tableAttributes = ""
this.t = ""
this.tableName = null
this.tableWhere = null
this.tableData = null
this.tablePage = null
this.tableLimit = null
this.tableOrder = null
this.tableGroup = null
this.tableAttributes = null
this.t = null
}
/**
@@ -166,7 +166,7 @@ module.exports = class Api {
}
const res = await this.models[this.tableName].findOne(
{
where: this.tableWhere,
where : this.tableWhere,
transaction: this.t
}
)
@@ -184,12 +184,12 @@ module.exports = class Api {
}
const res = await this.models[this.tableName].findAll(
{
where: this.tableWhere,
offset: (this.tablePage && this.tableLimit) ? this.tablePage - 1 * this.tableLimit : null,
limit: this.tableLimit,
order: this.tableOrder || [['updatedAt', 'DESC']], // 时间排序
group: this.tableGroup,
attributes: this.tableAttributes,
where : this.tableWhere,
offset : (this.tablePage && this.tableLimit) ? this.tablePage - 1 * this.tableLimit : null,
limit : this.tableLimit,
order : this.tableOrder || [['updatedAt', 'DESC']], // 时间排序
group : this.tableGroup,
attributes : this.tableAttributes,
transaction: this.t
}
)
@@ -210,8 +210,8 @@ module.exports = class Api {
}
const res = await this.models[this.tableName].findOrCreate(
{
defaults: this.tableData,
where: this.tableWhere,
defaults : this.tableData,
where : this.tableWhere,
transaction: this.t
}
)
@@ -232,12 +232,12 @@ module.exports = class Api {
}
const {count, rows} = await this.models[this.tableName].findAndCountAll(
{
where: this.tableWhere,
offset: (this.tablePage && this.tableLimit) ? this.tablePage - 1 * this.tableLimit : null,
limit: this.tableLimit,
order: this.tableOrder || [['updatedAt', 'DESC']], // 时间排序
group: this.tableGroup,
attributes: this.tableAttributes,
where : this.tableWhere,
offset : (this.tablePage && this.tableLimit) ? this.tablePage - 1 * this.tableLimit : null,
limit : this.tableLimit,
order : this.tableOrder || [['updatedAt', 'DESC']], // 时间排序
group : this.tableGroup,
attributes : this.tableAttributes,
transaction: this.t
}
)
@@ -264,7 +264,7 @@ module.exports = class Api {
let res = await this.models[this.tableName].findOne(
{
where: this.tableWhere,
where : this.tableWhere,
transaction: this.t
}
)
@@ -279,7 +279,7 @@ module.exports = class Api {
await this.models[this.tableName].update(
data,
{
where: this.tableWhere,
where : this.tableWhere,
transaction: this.t
}
)
@@ -296,14 +296,14 @@ module.exports = class Api {
await this.models[this.tableName].decrement(
this.tableData,
{
where: this.tableWhere,
where : this.tableWhere,
transaction: this.t
}
)
res = await this.models[this.tableName].findOne(
{
where: this.tableWhere,
where : this.tableWhere,
transaction: this.t
}
)
@@ -329,7 +329,7 @@ module.exports = class Api {
}
let res = await this.models[this.tableName].findOne(
{
where: this.tableWhere,
where : this.tableWhere,
transaction: this.t
}
)
@@ -344,7 +344,7 @@ module.exports = class Api {
await this.models[this.tableName].update(
data,
{
where: this.tableWhere,
where : this.tableWhere,
transaction: this.t
}
)
@@ -361,14 +361,14 @@ module.exports = class Api {
await this.models[this.tableName].increment(
this.tableData,
{
where: this.tableWhere,
where : this.tableWhere,
transaction: this.t
}
)
res = await this.models[this.tableName].findOne(
{
where: this.tableWhere,
where : this.tableWhere,
transaction: this.t
}
)
@@ -387,10 +387,10 @@ module.exports = class Api {
const res = await this.models[this.tableName].count(
this.tableData,
{
where: this.tableWhere,
order: this.tableOrder || [['updatedAt', 'DESC']], // 时间排序
group: this.tableGroup,
attributes: this.tableAttributes,
where : this.tableWhere,
order : this.tableOrder || [['updatedAt', 'DESC']], // 时间排序
group : this.tableGroup,
attributes : this.tableAttributes,
transaction: this.t
}
)
@@ -408,10 +408,10 @@ module.exports = class Api {
const res = await this.models[this.tableName].sum(
this.tableData,
{
where: this.tableWhere,
order: this.tableOrder || [['updatedAt', 'DESC']], // 时间排序
group: this.tableGroup,
attributes: this.tableAttributes,
where : this.tableWhere,
order : this.tableOrder || [['updatedAt', 'DESC']], // 时间排序
group : this.tableGroup,
attributes : this.tableAttributes,
transaction: this.t
}
)
@@ -429,10 +429,10 @@ module.exports = class Api {
const res = await this.models[this.tableName].max(
this.tableData,
{
where: this.tableWhere,
order: this.tableOrder || [['updatedAt', 'DESC']], // 时间排序
group: this.tableGroup,
attributes: this.tableAttributes,
where : this.tableWhere,
order : this.tableOrder || [['updatedAt', 'DESC']], // 时间排序
group : this.tableGroup,
attributes : this.tableAttributes,
transaction: this.t
}
)
@@ -450,10 +450,10 @@ module.exports = class Api {
const res = await this.models[this.tableName].min(
this.tableData,
{
where: this.tableWhere,
order: this.tableOrder || [['updatedAt', 'DESC']], // 时间排序
group: this.tableGroup,
attributes: this.tableAttributes,
where : this.tableWhere,
order : this.tableOrder || [['updatedAt', 'DESC']], // 时间排序
group : this.tableGroup,
attributes : this.tableAttributes,
transaction: this.t
}
)
+16 -4
View File
@@ -1,11 +1,11 @@
module.exports = {
database: "bamboo",
username: "bamboo",
password: "bamboo",
username: "root",
password: "123456",
options: {
dialect: 'mysql',
host: "192.168.1.26",
port: 3306,
host: "127.0.0.1",
port: 3357,
// 禁用日志记录或提供自定义日志记录功能;默认值:console.log
// logging: false,
// model的全局配置
@@ -44,4 +44,16 @@ module.exports = {
},
},
path:"app/*/model/*.js",
sqlite:{
host: 'localhost',
dialect: 'sqlite',
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
},
storage: './database.sqlite',
operatorsAliases: false
}
}
+12 -5
View File
@@ -2,6 +2,7 @@
* mysql/sequelize
*
* 参考文档:
* https://demopark.github.io/sequelize-docs-Zh-CN/
* https://sequelize.org/
* https://sequelize.org/api/v6/identifiers
* https://www.sequelize.com.cn/
@@ -10,6 +11,7 @@ const config = require("./config")
const Sequelize = require("sequelize");
const operatorsAliases = require("./operatorsAliases");
const Api = require("./api");
const Tool = require("./tool.js");
module.exports = async (app) => {
const {database, username, password, options,} = config
const sequelize = new Sequelize(database, username, password, {
@@ -27,11 +29,11 @@ module.exports = async (app) => {
model[key] = res.model[key]
}
model['id'] = {
type: Sequelize.INTEGER,
comment: '表自增id',
allowNull: false,
unique: 'id',
primaryKey: true,
type : Sequelize.INTEGER,
comment : '表自增id',
allowNull : false,
unique : 'id',
primaryKey : true,
autoIncrement: true,
}
sequelize.define(parse.name, model)
@@ -41,6 +43,10 @@ module.exports = async (app) => {
app.models = sequelize.models
const api = new Api(sequelize, sequelize.models)
app.db = api
app.db.tool = new Tool(app, sequelize)
//全局变量
app.alias["$db"] = app.db
// console.log(api);
// console.log(await app.db.table("User").find());
@@ -60,6 +66,7 @@ module.exports = async (app) => {
}
})
// await app.db.tool.reduction()
})
+50
View File
@@ -0,0 +1,50 @@
const config = require("./config")
import mysqldump from 'mysqldump';
const Importer = require('mysql-import');
module.exports = class {
constructor(app, sequelize) {
this.app = app
this.sequelize = sequelize
this.file = this.app.root + '/' + config.database + '.sql'
}
//备份数据库所有表
async backup(file) {
this.file = file || this.app.root + '/' + config.database + '.sql'
console.log('备份数据库中...');
await mysqldump({
connection: {
host : config.options.host,
port : config.options.port,
user : config.username,
password: config.password,
database: config.database,
},
dumpToFile: this.file,
});
console.log('备份数据库完成:', this.file);
}
//还原备份sql文件
async reduction() {
console.time("reduction")
//先备份旧数据
await this.backup(this.app.root + '/' + 'extend/mysql/backup/' + Date.now() + '.sql')
//清空数据库
await this.sequelize.drop()
//导入sql文件
const importer = new Importer({
host : config.options.host,
port : config.options.port,
user : config.username,
password: config.password,
database: config.database,
});
this.file = this.app.root + '/' + config.database + '.sql'
await importer.import(this.file)
console.timeEnd("reduction")
}
}
+2
View File
@@ -0,0 +1,2 @@
module.exports = {
}
+10
View File
@@ -0,0 +1,10 @@
/**
* 参数验证插件
*/
const config = require("./config")
const Parameter = require('parameter');
const parameter = new Parameter();
module.exports = async (app) => {
app.parameter = parameter
app.alias["$parameter"] = app.parameter
}
+3 -1
View File
@@ -11,5 +11,7 @@ module.exports = async (app) => {
const redis = new Redis(config);
app.redis = redis
app.Redis = Redis
//全局变量
app.alias["$redis"] = app.redis
app.alias["$Redis"] = app.Redis
}
+3 -1
View File
@@ -1,3 +1,5 @@
module.exports = {
path:"app/*/io/*.js",
path: "app/*/io/*.js",
port: 3210,
test_port: 3211,
}
+37 -8
View File
@@ -7,11 +7,16 @@
*/
const config = require("./config")
const path = require('path')
const uuid = require("uuid");
module.exports = async (app) => {
const parameter = app.parameter
const server = require('http').createServer(app.callback());
const io = require('socket.io')(server);
const io = require('socket.io')(server, {cors: true});
// let leaveRoom = () => {
// }
let list = await app.load(config.path)
app.io = io
app.alias["$io"] = app.io
//等待所有插件载入完成后
app.willReadyList.push(async () => {
//默认命名空间
@@ -24,17 +29,35 @@ module.exports = async (app) => {
}
});
console.log('连接=>', "id:" + socket.id);
//监听disconnect事件
socket.on('disconnect', (eventName, callback) => {
console.log('断开=X', "id:" + socket.id)
})
// socket.on('disconnect', (eventName, callback) => {
// console.log('断开=X', "id:" + socket.id)
// leaveRoom(socket, {msg: '', onname: 'leaveRoom', callback})
// })
for (let el of list) {
//空间名称
// const namespace = path.basename(path.resolve(el.parse.dir, '..'))
//事件名称
const onname = el.parse.name
socket.on(onname, (msg, callback) => {
el.res(app, msg, callback)
// if (onname === 'leaveRoom') {
// //离开房间处理
// leaveRoom = (socket, {msg, onname, callback}) => el.res.fun(socket, {msg, onname, callback})
// }
socket.on(onname, (msg, callback, anotherSocketId) => {
console.log('anotherSocketId', socket.id);
const validate = parameter.validate(el.res.params, msg);
if (validate) {
socket.emit('error', {
event: onname,
res : app.res.error(validate, "参数验证不通过", 204)
})
console.error('socket', socket.id, msg, onname, app.res.error(validate, "参数验证不通过", 204));
// ctx.body = app.res.error(validate, "参数验证不通过", 204)
} else {
el.res.fun(socket, {msg, onname, callback})
}
})
}
});
@@ -45,9 +68,15 @@ module.exports = async (app) => {
//覆盖启动方法
app.startServer = () => {
// 监听端口
app.startServer = server.listen(3000, () => {
console.log('listening on *:3000');
const port = (process.env.NODE_ENV === 'test' && config.test_port) || config.port || 3000
const baseURL = "http://127.0.0.1"
app.config.port = port
app.config.baseURL = baseURL
app.server = server.listen(port, () => {
console.log(`http 服务: ${baseURL}:${port}`);
console.log(`socket 服务: ${baseURL}:${port}`);
});
}
}