-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
88 lines (74 loc) · 1.83 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const Koa = require('koa');
const Router = require('koa-router');
const bodyParser = require('koa-bodyparser');
const cors = require('koa2-cors');
const config = require('./config.json');
const Email = require('./email');
const app = new Koa();
const router = new Router();
app.use(cors({
origin: "*"
}));
// x-response-time
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
ctx.set('X-Response-Time', `${ms}ms`);
});
// logger
app.use(async (ctx, next) => {
const start = Date.now();
await next();
const ms = Date.now() - start;
console.log(`${ctx.method} ${ctx.url} - ${ms}`);
});
app.use(bodyParser());
router.get('/', (ctx, next) => {
return ctx.body = {
code: 'send email'
}
});
router.post('/send', async (ctx, next) => {
const data = ctx.request.body;
const verify = ["from", "to", "subject"];
for (const item of verify) {
if(data[item] === "" || data[item] === undefined) {
return ctx.body = {
code: 500,
message: "缺少参数" + item
};
}
}
try {
return ctx.body = await Email({
from: data.from,
to: data.to,
subject: data.subject,
text: data.text || '',
html: data.html || '',
});
} catch (error) {
return ctx.body = {
code: error.responseCode,
res: error.response
}
}
return ctx.body = {
code: 0
}
});
app
.use(router.routes())
.use(router.allowedMethods());
app.use(async ctx => {
ctx.body = {
code: 404
}
});
app.listen(config.port || 3000, function() {
console.log("starting at http://localhost:" + (config.port || 3000));
});
app.on('error', err => {
log.error('server error', err)
});