Compare commits

...

No commits in common. "f79eccb11073384a9e7bf76c60435327e7803617" and "2fae55c8af4f08ae30e608782d4e8f8633f98852" have entirely different histories.

33 changed files with 277 additions and 7255 deletions

2
initProject.ps1 Normal file
View File

@ -0,0 +1,2 @@
nvm
yarn

7241
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{
"name": "koa2-template",
"version": "0.0.1",
"version": "1.0.1",
"description": "init a project with me",
"main": "index.js",
"scripts": {

53
public/css/reset.css Normal file
View File

@ -0,0 +1,53 @@
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
margin: 0;
padding: 0;
border: 0;
font-size: 100%;
font: inherit;
vertical-align: baseline;
text-decoration: none;
}
/* HTML5 display-role reset for older browsers */
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
display: block;
}
body {
line-height: 1;
font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB",
"Microsoft YaHei", "微软雅黑", Arial, sans-serif;
}
ol,
ul {
list-style: none;
}
blockquote,
q {
quotes: none;
}
blockquote:before,
blockquote:after,
q:before,
q:after {
content: "";
content: none;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
/*清除浮动*/
.clearfix:before,
.clearfix:after {
content: "";
display: block;
visibility: hidden;
clear: both;
}
/*容器*/
.container {
margin: 10px auto 0px;
width: 95%;
}

View File

@ -0,0 +1,24 @@
```bash
.
├── node_modules
├── public 静态资源
├── src
│ ├── index.js 项目入口文件
│ ├── app 业务应用
│ ├── config 业务配置
│ ├── routers 路由
│ ├── middlewares 中间件()
│ ├── controller 控制器(业务方法)
│ ├── services 数据库交互
│ ├── models (数据库)模型对象
│ ├── db 数据库连接对象
│ ├── constant 常数定义
│ ├── util 工具函数
│ └── views 渲染模板
├── test
│ ├── .example.http
│ └── redis.test.js
├── package.json
├── readme.md
└── readme.en.md
```

1
scripts/clean.ps1 Normal file
View File

@ -0,0 +1 @@
# 删除项目中的 占位/示例 文件(.example.*),不影响项目内容

View File

@ -6,7 +6,7 @@ const KoaStatic = require("koa-static");
const parameter = require("koa-parameter");
require("../config/env.config"); // 加载配置
const router = require("../route"); // 加载路由
const router = require("../routers"); // 加载路由
const errHandler = require("./error.handler"); // 加载自定义异常
const app = new Koa();

View File

@ -1,2 +1,3 @@
const { config } = require("dotenv");
config();
config({ path: "./src/config/.env" });

View File

@ -1,8 +1,12 @@
const {d} = require('../model/example')
const { d } = require("../models/user");
class UserController {
async register(ctx, next) {
ctx.json({ code: 0, message: "success" });
}
async getUserList(ctx, next) {
ctx.json({ code: 0, message: "success" });
}
}
module.exports = new UserController();

View File

@ -1,2 +0,0 @@
// connect to db
// use

27
src/db/mariadb.js Normal file
View File

@ -0,0 +1,27 @@
// connect to third-service of database or other.
const { Sequelize } = require("sequelize");
const {
MARIA_DIALECT,
MARIA_HOST,
MARIA_PORT,
MARIA_DBNAME,
MARIA_USRNAME,
MARIA_PASSWD,
} = process.env;
const seq = new Sequelize(MARIA_DBNAME, MARIA_USRNAME, MARIA_PASSWD, {
host: MARIA_HOST,
port: MARIA_PORT,
dialect: 'mariadb',
});
seq.authenticate()
.then(() => {
console.log('数据库连接成功')
})
.catch(err => {
console.log('数据库连接失败', err)
})
module.exports = seq;

49
src/db/redis.js Normal file
View File

@ -0,0 +1,49 @@
const redis = require("redis");
// require("../config/env.config");
const { REDIS_HOST, REDIS_PORT, REDIS_DBNAME, REDIS_USER, REDIS_PASSWD } =
process.env; // REDIS_USER 和 REDIS_PASSWD需要服务器配置ACL用户名密码
const URL = `redis://${REDIS_USER}:${REDIS_PASSWD}@${REDIS_HOST}:${REDIS_PORT}/${REDIS_DBNAME}`;
// https://github.com/redis/node-redis/tree/master/docs
// module.exports = redis.createClient({URL});
const client = redis.createClient({
// url: URL,
socket: { host: REDIS_HOST, port: REDIS_PORT },
password: REDIS_PASSWD,
// database: REDIS_DBNAME,
// legacyMode: true, // 语法向后(v3)部分兼容
});
client.on("error", (err) => console.log(`redis client ~ Error ${err}`));
client.on("connect", () => console.log("redis client ~ connect"));
client.on("reconnecting", () => console.log("redis client ~ reconnecting"));
client.on("ready", () => console.log("redis client ~ ready"));
client.on("end", () => console.log("redis client ~ end"));
client.connect();
client.ping();
// try {
// } catch (error) {
// console.log(error);
// }
module.exports = client;
//* 方式二redis 连接池
//! unusable
/* var redisPool = require("redis-connection-pool")("myRedisPool", {
host: REDIS_HOST, // default
port: REDIS_PORT, //default
max_clients: 30, // defalut
perform_checks: false, // checks for needed push/pop functionality
database: 0, // database number to use
options: {
auth_pass: REDIS_PASSWD,
}, //options for createClient of node-redis, optional
});
redisPool.set("test-key", "foobar", function (err) {
redisPool.get("test-key", function (err, reply) {
console.log(reply); // 'foobar'
});
}); */

View File

@ -2,6 +2,6 @@ const app = require("./app/index.js");
const { APP_PORT } = process.env;
app.listen(APP_PORT, () => {
console.log(`server is running on http://localhost:${APP_PORT}`);
app.listen(APP_PORT ?? 3000, () => {
console.log(`server is running on http://localhost:${APP_PORT ?? 3000}`);
});

View File

@ -1 +0,0 @@
const dbConnector = require('../db/example')

30
src/models/user.js Normal file
View File

@ -0,0 +1,30 @@
const { DataTypes } = require('sequelize')
const seq = require('../db/mariadb')
// 创建模型(Model user -> 数据库表 users)
const User = seq.define('user', {
// id 会被sequelize自动创建, 管理
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true,
comment: '用户名, 唯一',
},
password: {
type: DataTypes.CHAR(64),
allowNull: false,
comment: '密码',
},
is_admin: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: 0,
comment: '是否为管理员: 0 不是管理员(默认); 1 是管理员',
},
})
// 强制同步数据库(创建数据表)
// User.sync({ force: true })
module.exports = User

4
src/routers/user.js Normal file
View File

@ -0,0 +1,4 @@
const Router = require("koa-router");
const router = new Router({ prefix: "/user" });
router.post("/list", getUserList);

View File

@ -1,5 +0,0 @@
const ExampleModel = require('../model/example')
class ExampleService {}
module.exports = new ExampleService();

29
src/services/redis.js Normal file
View File

@ -0,0 +1,29 @@
const redisClient = require("../../db/redis");
/**
Object.prototype.toString = function () {
return JSON.stringify(this);
};
*/
class RedisService {
client = redisClient;
save2Redis(key, value) {
redisClient.set(key, value);
}
getByKey(key, callback = null) {
if (callback) {
redisClient.get(key, callback);
} else {
redisClient.get(key, (err, value) => {
if (err) return null;
console.log(value);
// return value;
});
}
}
}
module.exports = new RedisService();

42
src/services/user.js Normal file
View File

@ -0,0 +1,42 @@
const User = require('../models/user')
class UserService {
async createUser(user_name, password) {
// 插入数据
// await表达式: promise对象的值
const res = await User.create({ user_name, password })
// console.log(res)
return res.dataValues
}
async getUerInfo({ id, user_name, password, is_admin }) {
const whereOpt = {}
id && Object.assign(whereOpt, { id })
user_name && Object.assign(whereOpt, { user_name })
password && Object.assign(whereOpt, { password })
is_admin && Object.assign(whereOpt, { is_admin })
const res = await User.findOne({
attributes: ['id', 'user_name', 'password', 'is_admin'],
where: whereOpt,
})
return res ? res.dataValues : null
}
async updateById({ id, user_name, password, is_admin }) {
const whereOpt = { id }
const newUser = {}
user_name && Object.assign(newUser, { user_name })
password && Object.assign(newUser, { password })
is_admin && Object.assign(newUser, { is_admin })
const res = await User.update(newUser, { where: whereOpt })
// console.log(res)
return res[0] > 0 ? true : false
}
}
module.exports = new UserService()

5
src/util/bcrypt.js Normal file
View File

@ -0,0 +1,5 @@
const bcryptjs = require("bcryptjs");
class Bcrypt {}
module.exports = new Bcrypt();

0
test/.http Normal file
View File

0
test/.rest Normal file
View File