mikujs
v1.5.4
Published
a nodejs framework
Downloads
28
Readme
mikujs
A Node.js framework.
Installation
$ npm install --save mikujs
CLI
$ npm install -g mikujs-cli
Note
Necessary directories description.
- configs Set all config
.json
files. - static Static files.
- schedules Schedules files.
Component
Boot
const Boot = require('mikujs').Boot;
Boot({
cors: true, // default value is false
port: 3010, // default value is 3000
middlewares: [], // default value is []
apis: [], // default value is []
unTokenPaths: [], // default value is []
});
Api
const Api = require('mikujs').Api();
const api = new Api();
api.get({
url: '/test',
service: async () => {
return 'test message';
},
});
api.post({
url: '/test',
service: async () => {
return 'test message';
},
});
api.upload({
url: '/test',
fieldName: 'file',
service: async (ctx) => {
const fileName = ctx.req.files[0].filename;
return fileName;
},
});
// default paramName is fileName
api.download({
url: '/test',
});
api.download({
url: '/test',
paramName: 'fileName1',
});
If you want to validate params, see more from joi, For example
api.get({
url: '/test',
validate: {
name: {
required: true,
},
value: {
type: 'number',
min: 1,
},
},
service: async () => {
return 'test message';
},
});
If you do want to set allow file suffix, For example
api.upload({
url: '/test',
fieldName: 'file',
fileSuffixs: ['txt'],
service: async (ctx) => {
const fileName = ctx.req.files[0].filename;
return fileName;
},
});
If you do want to set file size, For example
api.upload({
url: '/test',
fileSize: 2,
service: async (ctx) => {
const files = [];
ctx.req.files.forEach((file) => {
files.push(file.filename);
});
return files;
},
});
If you do want to set file limit, For example
api.upload({
url: '/test',
fileLimit: {
fileSize: 1048576, // 1MB = 1024 * 1024Byte = 1048576Byte
files: 5,
},
service: async (ctx) => {
const fileName = ctx.req.files[0].filename;
return fileName;
},
});
If you do want to upload memory, For example
api.upload({
url: '/test',
memory: true,
service: async (ctx) => {
const { originalname, buffer } = ctx.req.files[0];
const fileSuffix = File.suffix(originalname);
const fileName = await AliOss.upload('test', fileSuffix, buffer);
return fileName;
}
});
If you do want to have security, For example
api.get({
url: '/test',
security: {
roles: ['roleCode'],
permissions: ['permissionCode'],
},
service: async () => {
return 'test message';
},
});
If you do want to wechat pay notify, For example
api.weChatPayNotify({
url: '/test',
type: 'refund',
service: async (ctx) => {
const info = ctx.request.weixin;
return 'error message' || ''; // '' is success
},
});
Log
const Log = require('mikujs').Log;
Log.debug('debug');
Log.info('info');
Log.error('error');
CoreError
const CoreError = require('mikujs').CoreError;
throw new CoreError('error message');
Redis
const Redis = require('mikujs').Redis;
Redis.redis; // redis instantce
Redis.set(key, value);
Redis.set(key, value, expireTime); // expireTIme unit: second
const value = await Redis.get(key);
Token
const Token = require('mikujs').Token;
const token = Token.set(tokenValue);
If you do want to set security, For example
const token = Token.set({
security: {
roles: ['roleCode'],
permissions: ['permissionCode'],
},
});
Lodash
See more from lodash
File
const File = require('mikujs').File;
const f = File.name(fileName); // remove file suffix
const s = File.suffix(fileName); // get file suffix
const obj = File.convertToObject(path); // convert to object from path
const arr = File.covertToArray(path); // convert to array from path
File.del(path); // delete file
File.exist(path); // file exists
File.write(path, data); // write file
File.read(path); // read file
File.chmod(path, mode); // chmod file
Moment
See more from moment
Model
const Model = require('mikujs').Model;
Model.sequelize; // sequelize object
Model.define(tableName, fields); // define model
Model.string(length);
Model.char(length);
Model.boolean();
Model.integer();
Model.double();
Model.enums();
Model.date();
Model.text();
For Example
const Model = require('mikujs').Model;
// define test model
const test = Model.define('test', {
name: {
type: Model.string(50),
allowNull: false,
},
value: {
type: Model.integer(),
allowNull: false,
},
});
Digest
const Digest = require('mikujs').Digest;
const value = Digest.md5('123456');
// 3: digest count, default is 1
const value = Digest.md5('123456', 3);
Captcha
const Captcha = require('mikujs').Captcha;
const captchaValue = await Captcha.generate(mobileNumber);
const result = await Captcha.check(captchaValue, mobileNumber);
If you want to set expired time, For example
const captchaValue = await Captcha.generate('159xxxx8250', {
expired: 20 * 60 // twenty minutes
});
Http
const Http = require('mikujs').Http;
const result = await Http.http(opts);
const result = await Http.get(opts);
const result = await Http.post(opts);
const result = await Http.put(opts);
const result = await Http.del(opts);
For Example
const result = await Http.get({
url: 'http://www.baidu.com',
headers: {},
data: {},
});
If you want to use form data, For example
const FormData = require('form-data');
const formData = new FormData();
formData.append('driveId', driveId);
formData.append('path', fileName);
formData.append('file', buffer);
const result = await Http.post({
url: '/upload',
headers: {
'Access-Token': 'xxxx',
...formData.getHeaders(),
},
data: formData,
maxContentLength: 52428800, // 50M
dealError: async (err) => {
if (err.response) {
console.log(err.response.status);
}
},
});
Push
const Push = require('mikujs').Push;
const aliasValue = Push.alias(value);
Push.simple(content, opts);
For Example
Push.simple('test', {
platform: 'ios',
});
Uuid
const Uuid = require('mikujs').Uuid;
Uuid.generate(needConnector);
For Example
Uuid.generate();
If you want to need connector like '-', For example
Uuid.generate('-');
Socket
const Socket = require('mikujs').Socket;
Socket.on(name, event);
Socket.emit(name, value);
For Example
Socket.on('chat message', (msg) => {
console.log(`message: ${msg}`);
});
Socket.emit('chat message', 'test');
Validator
See more from validator
Util
const Util = require('mikujs').Util;
// transaction
await Util.transaction(async(t) => {
await test.create({
name: 'test',
value: 1,
}, {
transaction: t,
});
const isUpdated = await test.update({
value: 2,
}, {
where: {
name: 'test',
},
transaction: t,
});
if (!isUpdated[0]) {
// if has update, must manual rollback
await t.rollback();
}
});
// datetime format
Util.dateTimeFormat(value);
// date format
Util.dateFormat(value);
// time format
Util.timeFormat(value);
// add 2 days
Util.addDays({
days: 2,
});
// minus 1 days
Util.minusDays();
// check mobile
Util.isMobile(mobile);
// covert china characters to first letter
Util.coverToFirstLetter('中心');
// findAll or page
opts = opts || {};
const where = {};
const page = opts.page || false;
const current = opts.current || 1;
const size = opts.size || 10;
const departments = await Util.findAllOrPage(departmentModel, {
page,
current,
size,
}, {
order: [
['sort', 'desc'],
],
where,
include: [
{
model: departmentModel,
as: 'parent',
},
],
});
return departments;
const WeChat = require('mikujs').WeChat;
const redirectUrl = WeChat.generateRedirectUrl(redirectUrl, state, scope);
const redirectUrlForWebsite = WeChat.generateRedirectUrlForWebsite(redirectUrl, state, scope);
const token = await WeChat.getAccessTokenAndOpenId(code);
const jsConfig = await WeChat.getJsConfig(jsApiList, url, debug);
Joi
See more from joi
AliOss
const AliOss = require('mikujs').AliOss;
AliOss.upload('test', 'jpg', buffer);
WeChatPay
const WeChatPay = require('mikujs').WeChatPay;
const result = await WeChatPay.getPayParams(outTradeNo, body, totalFee, openId);
const result = await WeChatPay.getAppParams(outTradeNo, body, totalFee);
const result = await WeChatPay.unifiedOrder(outTradeNo, body, totalFee, openId);
const result = await WeChatPay.refundOrder(outTradeNo, outRefundNo, totalFee, refundFee);
Schedule
See more from node-schedule
WeChatEnterPrise
const WeChatEnterPrise = require('mikujs').WeChatEnterPrise;
WeChatEnterPrise.message('message content');
Cheerio
See more from cheerio
Pinyin
See more from pinyin
Bagpipe
const Bagpipe = require('mikujs').Bagpipe;
Bagpipe.downFile('http://xxxxxx.jpg', 'download/bagpipe.jpg');
Gt
const Gt = require('mikujs').Gt;
await Gt.register(); // get html need param
await Gt.vertify(challenge, validate, seccode); // second vertify
Random
const Random = require('mikujs').Random;
Random.generate(length);
For Example
Random.generate();
If you want to change length like 6, For example
Random.generate(6);
Math
See more from mathjs
Excel
See more from exceljs
// write
const Excel = require('mikujs').Excel;
const columns = [
{ header: '列名', key: 'columnKey', width: 100 },
];
const rows = [
{ columnKey: 'lalala' },
];
await Excel.simpleWrite('test.xlsx', columns, rows);
// read
const cellValues = await Excel.simpleRead('test2.xlsx', 3);
Dict
const Dict = require('mikujs').Dict;
// wrap
Dict.wrap({
// 大图
BIG: {
code: 'NEWS_TYPE_BIG',
description: '大图',
},
// 右图
RIGHT: {
code: 'NEWS_TYPE_RIGHT',
description: '右图',
},
// 三张图
THREE: {
code: 'NEWS_TYPE_THREE',
description: '三张图',
},
});
Chokidar
const Chokidar = require('mikujs').Chokidar;
const watcher = await Chokidar.init('/Users/frank/Downloads/watch');
watcher
.on('add', path => console.log(`File ${path} has been added`))
.on('change', path => console.log(`File ${path} has been changed`))
.on('unlink', path => console.log(`File ${path} has been removed`))
.on('addDir', path => console.log(`Directory ${path} has been added`))
.on('unlinkDir', path => console.log(`Directory ${path} has been removed`));