Skip to content

Commit 6d23022

Browse files
committed
add service folder
1 parent d805353 commit 6d23022

16 files changed

Lines changed: 4076 additions & 0 deletions

File tree

service/.gitignore

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
# Logs
2+
logs
3+
*.log
4+
npm-debug.log*
5+
yarn-debug.log*
6+
yarn-error.log*
7+
8+
# Runtime data
9+
pids
10+
*.pid
11+
*.seed
12+
*.pid.lock
13+
14+
# Directory for instrumented libs generated by jscoverage/JSCover
15+
lib-cov
16+
17+
# Coverage directory used by tools like istanbul
18+
coverage
19+
20+
# nyc test coverage
21+
.nyc_output
22+
23+
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
24+
.grunt
25+
26+
# Bower dependency directory (https://bower.io/)
27+
bower_components
28+
29+
# node-waf configuration
30+
.lock-wscript
31+
32+
# Compiled binary addons (https://nodejs.org/api/addons.html)
33+
build/Release
34+
35+
# Dependency directories
36+
node_modules/
37+
jspm_packages/
38+
39+
# Typescript v1 declaration files
40+
typings/
41+
42+
# Optional npm cache directory
43+
.npm
44+
45+
# Optional eslint cache
46+
.eslintcache
47+
48+
# Optional REPL history
49+
.node_repl_history
50+
51+
# Output of 'npm pack'
52+
*.tgz
53+
54+
# Yarn Integrity file
55+
.yarn-integrity
56+
57+
# dotenv environment variables file
58+
.env

service/app.js

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
const Koa = require("koa");
2+
const app = new Koa();
3+
const json = require("koa-json");
4+
const onerror = require("koa-onerror");
5+
const bodyparser = require("koa-bodyparser");
6+
const logger = require("koa-logger");
7+
const router = require("./routes/index");
8+
const errorHandle = require("./util/error.js");
9+
const koaJwt = require("koa-jwt");
10+
const config = require("./config/index");
11+
const filterApi = require("./config/filterApi");
12+
const util = require("./util/index");
13+
const { connect } = require("./model/init");
14+
onerror(app);
15+
app.use(
16+
bodyparser({
17+
enableTypes: ["json", "form", "text"]
18+
})
19+
);
20+
app.use(json());
21+
app.use(logger());
22+
app.use(require("koa-static")(__dirname + "/public"));
23+
app.use(async (ctx, next) => {
24+
const start = new Date();
25+
await next();
26+
const ms = new Date() - start;
27+
console.log(`${ctx.method} ${ctx.url} - ${ms}ms`);
28+
});
29+
app.use(errorHandle);
30+
app.use(
31+
koaJwt({
32+
secret: config.secret,
33+
isRevoked: util.verify
34+
}).unless({
35+
path: [...filterApi]
36+
})
37+
);
38+
app.use(router.routes(), router.allowedMethods());
39+
(async () => {
40+
await connect();
41+
})();
42+
app.on("error", (err, ctx) => {
43+
console.error("server error", err, ctx);
44+
});
45+
46+
module.exports = app;

service/bin/www

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,90 @@
1+
#!/usr/bin/env node
2+
3+
/**
4+
* Module dependencies.
5+
*/
6+
7+
var app = require('../app');
8+
var debug = require('debug')('demo:server');
9+
var http = require('http');
10+
11+
/**
12+
* Get port from environment and store in Express.
13+
*/
14+
15+
var port = normalizePort(process.env.PORT || '3000');
16+
// app.set('port', port);
17+
18+
/**
19+
* Create HTTP server.
20+
*/
21+
22+
var server = http.createServer(app.callback());
23+
24+
/**
25+
* Listen on provided port, on all network interfaces.
26+
*/
27+
28+
server.listen(port);
29+
server.on('error', onError);
30+
server.on('listening', onListening);
31+
32+
/**
33+
* Normalize a port into a number, string, or false.
34+
*/
35+
36+
function normalizePort(val) {
37+
var port = parseInt(val, 10);
38+
39+
if (isNaN(port)) {
40+
// named pipe
41+
return val;
42+
}
43+
44+
if (port >= 0) {
45+
// port number
46+
return port;
47+
}
48+
49+
return false;
50+
}
51+
52+
/**
53+
* Event listener for HTTP server "error" event.
54+
*/
55+
56+
function onError(error) {
57+
if (error.syscall !== 'listen') {
58+
throw error;
59+
}
60+
61+
var bind = typeof port === 'string'
62+
? 'Pipe ' + port
63+
: 'Port ' + port;
64+
65+
// handle specific listen errors with friendly messages
66+
switch (error.code) {
67+
case 'EACCES':
68+
console.error(bind + ' requires elevated privileges');
69+
process.exit(1);
70+
break;
71+
case 'EADDRINUSE':
72+
console.error(bind + ' is already in use');
73+
process.exit(1);
74+
break;
75+
default:
76+
throw error;
77+
}
78+
}
79+
80+
/**
81+
* Event listener for HTTP server "listening" event.
82+
*/
83+
84+
function onListening() {
85+
var addr = server.address();
86+
var bind = typeof addr === 'string'
87+
? 'pipe ' + addr
88+
: 'port ' + addr.port;
89+
debug('Listening on ' + bind);
90+
}

service/config/filterApi.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
module.exports = [/\/login/, /\/register/];

service/config/index.js

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
module.exports = {
2+
secret: "[email protected]",
3+
mongoUrl: "mongodb://127.0.0.1:27017/fruitShop",
4+
userNumber: "Harhao",
5+
password: "1234567",
6+
expiresIn: {
7+
expiresIn: "2h"
8+
}
9+
};

service/controller/user.js

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
const userModel = require("../model/user.js");
2+
const config = require("../config/index.js");
3+
const util = require("../util/index");
4+
module.exports = {
5+
register: async (ctx, next) => {
6+
let { name, password, phone } = ctx.request.body;
7+
if (name && password) {
8+
password = util.createHash(password);
9+
const result = await new userModel({
10+
name: name,
11+
password: password,
12+
phone: phone
13+
}).save();
14+
console.log("register result is", result);
15+
if (!result)
16+
return (ctx.body = {
17+
code: "400",
18+
message: "register fail"
19+
});
20+
else
21+
return (ctx.body = {
22+
code: "200",
23+
message: "register success!"
24+
});
25+
}
26+
},
27+
login: async (ctx, next) => {
28+
const data = ctx.request.body;
29+
if (!data.name || !data.password) {
30+
return (ctx.body = {
31+
code: "",
32+
data: null,
33+
message: "the usernumber or password can't be null"
34+
});
35+
}
36+
data.password = util.createHash(data.password);
37+
const result = await userModel.find({
38+
name: data.name,
39+
password: data.password
40+
});
41+
if (result && result.length) {
42+
const token = util.sign(result);
43+
return (ctx.body = {
44+
code: "200",
45+
token: token,
46+
message: "login success"
47+
});
48+
} else {
49+
return (ctx.body = {
50+
code: "400",
51+
data: null,
52+
message: "usernumber or password is error"
53+
});
54+
}
55+
},
56+
getuserinfo: async (ctx, next) => {
57+
const { name } = ctx.request.query;
58+
if (name) {
59+
const result = await userModel.findOne({
60+
name: name
61+
});
62+
console.log(result);
63+
result
64+
? (ctx.body = { code: 200, data: result, message: "ok" })
65+
: (ctx.body = { code: 200, data: null, message: "ok" });
66+
} else {
67+
ctx.body = {
68+
code: 400,
69+
message: "name is null"
70+
};
71+
}
72+
}
73+
};

service/model/category.js

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
const mongoose = require("mongoose");
2+
const Schema = mongoose.Schema;
3+
const categorySchema = new Schema({
4+
id: {
5+
type: Number
6+
},
7+
parent_id: {
8+
type: Number
9+
},
10+
name: {
11+
type: String,
12+
default: ''
13+
},
14+
status: {
15+
type: Boolean,
16+
default: false
17+
},
18+
create_time: {
19+
type: Date,
20+
default: Date.now()
21+
},
22+
update_time: {
23+
type: Date,
24+
default: Date.now()
25+
}
26+
});
27+
module.exports = mongoose.model("category", categorySchema);

service/model/goods.js

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
const mongoose = require("mongoose");
2+
const Schema = mongoose.Schema;
3+
const ObjectId = Schema.Types.ObjectId;
4+
const goodsSchema = new Schema({
5+
id:{
6+
type:Number
7+
},
8+
category_id:{
9+
10+
}
11+
});
12+
module.exports = mongoose.model("goods", goodsSchema);

service/model/init.js

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
const mongoose = require("mongoose");
2+
const mongoUrl = require("../config/index").mongoUrl;
3+
function connectDB() {
4+
mongoose.connect(mongoUrl, { useNewUrlParser: true, useCreateIndex: true });
5+
}
6+
exports.connect = () => {
7+
connectDB();
8+
let maxConnectTimes = 0;
9+
return new Promise((resolve, reject) => {
10+
mongoose.connection.on("disconnected", () => {
11+
if (maxConnectTimes <= 3) {
12+
maxConnectTimes++;
13+
connectDB();
14+
} else {
15+
reject();
16+
throw new Error("数据库出现问题");
17+
}
18+
});
19+
mongoose.connection.on("error", err => {
20+
console.log("***********数据库错误***********");
21+
if (maxConnectTimes <= 3) {
22+
maxConnectTimes++;
23+
connectDB();
24+
} else {
25+
reject(err);
26+
throw new Error("数据库出现问题,程序无法搞定,请人为修理.....");
27+
}
28+
});
29+
mongoose.connection.once("open", () => {
30+
console.log("MogoDB connect success");
31+
resolve();
32+
});
33+
});
34+
};

0 commit comments

Comments
 (0)