Compare commits

...

9 Commits

17 changed files with 845 additions and 245 deletions

18
.vscode/launch.json vendored Normal file
View File

@@ -0,0 +1,18 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"envFile": "${workspaceFolder}/.env",
"skipFiles": [
"<node_internals>/**"
],
"program": "${workspaceFolder}\\src\\index.js"
}
]
}

3
.vscode/settings.json vendored Normal file
View File

@@ -0,0 +1,3 @@
{
"Codegeex.RepoIndex": true
}

20
index.html Normal file
View File

@@ -0,0 +1,20 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://libs.cdnjs.net/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(() => {
$.getJSON('/ten', (data) => {
$('#content').text(JSON.stringify(data));
})
})
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>

View File

@@ -1,4 +1,4 @@
@url = http://localhost:8001/api @url = http://localhost:8080/api
@json = Content-Type: application/json @json = Content-Type: application/json
### main ### main
@@ -10,23 +10,30 @@ GET {{url}}
GET {{url}}/user GET {{url}}/user
### ###
GET {{url}}/user/6592b261ec153ffe0080527f GET {{url}}/user/66e0fc98bfe90d5ebc373fad
### ###
POST {{url}}/user POST {{url}}/user
Content-Type: application/json {{json}}
{ {
"username": "dd", "username": "azj",
"password": "wwgweaerhgr", "password": "helloworld",
"truename": "Davie Dro" "truename": "Davie Dro"
} }
### ###
PUT {{url}}/user/6592b261ec153ffe0080527f PUT {{url}}/user/66e0fc4eb7f0bcce35db2755
{{json}} {{json}}
{ {
"truename": "张表4" "truename": "艾志坚"
} }
###
DELETE {{url}}/user/66e0fc98bfe90d5ebc373fad
###
GET http://172.31.2.82:25565

783
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -13,8 +13,8 @@
"author": "hbk01", "author": "hbk01",
"license": "GPL-3.0-or-later", "license": "GPL-3.0-or-later",
"dependencies": { "dependencies": {
"dotenv": "^16.3.1",
"express": "^4.18.2", "express": "^4.18.2",
"mongoose": "^8.0.3" "mongoose": "^8.0.3",
"nodemon": "^3.1.0"
} }
} }

18
pm2.config.cjs Normal file
View File

@@ -0,0 +1,18 @@
module.exports = {
apps: [{
name: "labplus-server",
script: "./src/index.js",
watch: [
"src"
],
ignore_watch: [
"node_modules"
],
env: {
"NODE_ENV": "production",
"PORT": 80,
// TODO: change to your own username and password
"DATABASE_URI": "mongodb://USERNAME:PASSWORD@localhost:27017/labplus",
}
}]
}

View File

@@ -1,13 +0,0 @@
export const apps = [{
name: "labplus-server",
script: "./src/index.js",
watch: [
"src"
],
ignore_watch: [
"node_modules"
],
env: {
"NODE_ENV": "production"
}
}]

58
src/controllers/sample.js Normal file
View File

@@ -0,0 +1,58 @@
import express from 'express'
import Sample from '../models/sample.js'
const router = express.Router()
// GET /sample
router.get('/', async (req, res) => {
let sample = await Sample.find({}).limit(10)
res.json(sample)
})
// GET /sample/:id
router.get('/:id', async (req, res) => {
let id = req.params.id
let sample = await Sample.findById(id)
res.json(sample)
})
// POST /sample
router.post('/', async (req, res) => {
let sample = new Sample(req.body)
await sample.save().then(() => {
res.json(sample)
}).catch((err) => {
res.json({ error: err })
})
})
// PUT /sample/:id
router.put('/:id', async (req, res) => {
let id = req.params.id
let sample = req.body
await Sample.findByIdAndUpdate(id, sample, { new: true }, (err, sample) => {
if (err) {
res.json({ error: err })
} else if (!sample) {
res.json({ error: `Sample ${id} not found` })
} else {
res.json(sample)
}
})
})
// DELETE /sample/:id
router.delete('/:id', async (req, res) => {
let id = req.params.id
await Sample.findByIdAndDelete(id, (err, sample) => {
if (err) {
res.json({ error: err })
} else if (!sample) {
res.json({ error: `Sample ${id} not found` })
} else {
res.json(sample)
}
})
})
export default router

View File

@@ -1,24 +1,29 @@
import express from "express" import express from "express"
import User from "../models/user.js" import User from "../models/user.js"
import Role from "../models/role.js"
import Status from "../models/status.js"
const router = express.Router() const router = express.Router()
router.get("/", async (req, res) => { router.get("/", async (req, res) => {
const a = await User.find({}) let user = await User.find({}).populate("status")
res.json(a) res.json(user)
}) })
router.get("/:id", (req, res) => { router.get("/:id", (req, res) => {
User.findById(req.params.id).then((user) => { User.findById(req.params.id).populate("status").then((user) => {
res.json(user) res.json(user)
}).catch((err) => { }).catch((err) => {
res.json({ error: err }) res.json({ error: err })
}) })
}) })
router.post("/", (req, res) => { router.post("/", async (req, res) => {
const user = new User(req.body) const user = new User(req.body)
user.save().then(() => { let status = new Status()
await status.save()
user.status = status
await user.save().then(() => {
res.json(user) res.json(user)
}).catch((err) => { }).catch((err) => {
res.json({ error: err }) res.json({ error: err })
@@ -26,17 +31,16 @@ router.post("/", (req, res) => {
}) })
router.put("/:id", async (req, res) => { router.put("/:id", async (req, res) => {
const user = await User.findByIdAndUpdate(req.params.id, req.body, { new: true }) await User.findByIdAndUpdate(req.params.id, req.body, { new: true }).then((user) => {
res.json(user) res.json(user)
}) })
})
router.delete("/:id", async (req, res) => { router.delete("/:id", async (req, res) => {
const user = await User.findByIdAndDelete(req.params.id).then(() => { await User.findByIdAndDelete(req.params.id)
res.json({ .populate("status")
"message": "User deleted successfully" .then((user) => {
}) res.json(user)
}).catch((err) => {
res.json({ error: err })
}) })
}) })

View File

@@ -1,22 +1,60 @@
import Express from "express" import Express from "express"
import dotenv from "dotenv"
import router from "./router.js" import router from "./router.js"
import mongoose from "mongoose" import mongoose from "mongoose"
dotenv.config()
const app = Express() const app = Express()
const PORT = process.env.PORT || 8080 const PORT = process.env.PORT || 8080
const DATABASE_URL = process.env.DATABASE_URL || "mongodb://localhost:27017/labplus"
mongoose.connect(DATABASE_URL) mongoose.connect(process.env.DATABASE_URI)
const db = mongoose.connection const db = mongoose.connection
db.on("error", (error) => console.error(error))
db.on("error", console.error.bind(console, "connection error:"))
db.once("open", () => console.log("Connected to Database")) db.once("open", () => console.log("Connected to Database"))
app.use(Express.json()) app.use(Express.json())
app.use(Express.urlencoded({ extended: true })) app.use(Express.urlencoded({ extended: true }))
// init premission groups
let permissions = {
user_create: {
level: 0, // 0: anyone, 1: user, 2: admin, 3: root
rule: "user_create",
description: "Create new user"
},
user_change_self_password: {
level: 1,
rule: "user_change_self_password",
description: "change self password"
},
user_change_password: {
level: 2,
rule: "user_change_password",
description: "change any user password"
},
user_change_admin_password: {
level: 3,
rule: "user_change_admin_password",
description: "change admin password"
}
}
import Permission from "./models/permission.js"
for (const key in permissions) {
if (Object.prototype.hasOwnProperty.call(permissions, key)) {
let element = new Permission(permissions[key])
element.save()
}
}
// TODO 这里有问题,
// init roles
// import Role from "./models/role.js"
// let r = new Role({
// name: "root",
// permissions: Permission.find({}).exec()
// })
// r.save()
// init router
app.use("/api", router) app.use("/api", router)
app.listen(PORT, () => { app.listen(PORT, () => {

View File

@@ -1,6 +1,7 @@
import { Schema, model } from 'mongoose' import { Schema, model } from 'mongoose'
const permissionSchema = new Schema({ const permissionSchema = new Schema({
level: { type: Number, required: true },
rule: { type: String, required: true }, rule: { type: String, required: true },
description: { type: String, required: true } description: { type: String, required: true }
}) })

View File

@@ -1,14 +1,9 @@
import { Schema } from 'mongoose' import { Schema, model } from 'mongoose'
import Permission from './permission.js'
const roleSchema = new Schema({ const roleSchema = new Schema({
name: { type: String, required: true }, name: { type: String, required: true },
permissions: [{ type: Schema.Types.ObjectId, ref: 'Permission' }], permissions:[{ type: Schema.Types.ObjectId, ref: Permission }],
status: {
deleted: { type: Boolean, default: false },
createAt: { type: Date, default: Date.now() },
deleteAt: { type: Date },
updateAt: { type: Date, default: Date.now() }
}
}) })
export default model('Role', roleSchema) export default model('Role', roleSchema)

24
src/models/sample.js Normal file
View File

@@ -0,0 +1,24 @@
import { Schema, model } from 'mongoose'
const sampleSchema = new Schema({
// L414-5KR-7-240703
// 产品名 L414-5KR
productName: { type: String },
// 批次号字符串 L414-5KR-7-240703
batchString: { type: String },
// 样品 ID L414-5KR-7-240703-01
id: { type: String },
// 送样时间
postTime: { type: Date, default: Date.now },
// 测试项目
testItem: { type: Array, default: [] },
status: { type: Schema.Types.ObjectId, ref: 'Status' }
})
export default model('Sample', sampleSchema)

12
src/models/status.js Normal file
View File

@@ -0,0 +1,12 @@
import { Schema, model } from 'mongoose'
const statusSchema = new Schema({
locked: { type: Boolean, default: false },
lockAt: { type: Date },
lockBy: { type: Schema.Types.ObjectId, ref: 'User' },
deleted: { type: Boolean, default: false },
createAt: { type: Date, default: Date.now() },
deleteAt: { type: Date },
updateAt: { type: Date, default: Date.now() }
})
export default model('Status', statusSchema)

View File

@@ -7,26 +7,18 @@ const userSchema = new Schema({
truename: { type: String, required: true }, // 真实名字 truename: { type: String, required: true }, // 真实名字
role: { type: Schema.Types.ObjectId, ref: 'Role' }, role: { type: Schema.Types.ObjectId, ref: 'Role' },
lastLogin: { type: Date }, lastLogin: { type: Date },
status: { status: { type: Schema.Types.ObjectId, ref: 'Status' }
locked: { type: Boolean, default: false },
lockAt: { type: Date },
lockBy: { type: Schema.Types.ObjectId, ref: 'User' },
deleted: { type: Boolean, default: false },
createAt: { type: Date, default: Date.now() },
deleteAt: { type: Date },
updateAt: { type: Date, default: Date.now() }
}
}) })
// TODO: IT CAN'T WORK ... // TODO: IT CAN'T WORK ...
userSchema.pre('deleteOne', { document: true }, () => { userSchema.pre(['deleteOne', 'findByIdAndDelete'], { document: true }, () => {
this.status.deleted = true this.status.deleted = true
this.status.deleteAt = Date.now() this.status.deleteAt = Date.now()
}) })
userSchema.pre(['findByIdAndUpdate', 'findOneAndUpdate'], (next) => { userSchema.pre(['findByIdAndUpdate', 'findOneAndUpdate'], (next) => {
this.status.updateAt = Date.now() this.status.updateAt = Date.now()
console.log("gdfg"); console.log("gdfg")
next() next()
}) })

View File

@@ -1,10 +1,12 @@
import express from "express" import express from "express"
import user from "./controllers/user.js" import user from "./controllers/user.js"
import sample from "./controllers/sample.js"
const router = express.Router({ const router = express.Router({
caseSensitive: true caseSensitive: true
}) })
router.use("/user", user) router.use("/user", user)
router.use("/sample", sample)
export default router export default router