forked from elgris/microservice-app-example
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
64 lines (56 loc) · 2.04 KB
/
server.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
'use strict';
const express = require('express')
const bodyParser = require("body-parser")
const jwt = require('express-jwt')
const ZIPKIN_URL = process.env.ZIPKIN_URL || 'http://127.0.0.1:9411/api/v2/spans';
const {Tracer,
BatchRecorder,
jsonEncoder: {JSON_V2}} = require('zipkin');
const CLSContext = require('zipkin-context-cls');
const {HttpLogger} = require('zipkin-transport-http');
const zipkinMiddleware = require('zipkin-instrumentation-express').expressMiddleware;
const logChannel = process.env.REDIS_CHANNEL || 'log_channel';
const redisClient = require("redis").createClient({
host: process.env.REDIS_HOST || 'localhost',
port: process.env.REDIS_PORT || 6379,
retry_strategy: function (options) {
if (options.error && options.error.code === 'ECONNREFUSED') {
return new Error('The server refused the connection');
}
if (options.total_retry_time > 1000 * 60 * 60) {
return new Error('Retry time exhausted');
}
if (options.attempt > 10) {
console.log('reattemtping to connect to redis, attempt #' + options.attempt)
return undefined;
}
return Math.min(options.attempt * 100, 2000);
}
});
const port = process.env.TODO_API_PORT || 8082
const jwtSecret = process.env.JWT_SECRET || "foo"
const app = express()
// tracing
const ctxImpl = new CLSContext('zipkin');
const recorder = new BatchRecorder({
logger: new HttpLogger({
endpoint: ZIPKIN_URL,
jsonEncoder: JSON_V2
})
});
const localServiceName = 'todos-api';
const tracer = new Tracer({ctxImpl, recorder, localServiceName});
app.use(jwt({ secret: jwtSecret }))
app.use(zipkinMiddleware({tracer}));
app.use(function (err, req, res, next) {
if (err.name === 'UnauthorizedError') {
res.status(401).send({ message: 'invalid token' })
}
})
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
const routes = require('./routes')
routes(app, {tracer, redisClient, logChannel})
app.listen(port, function () {
console.log('todo list RESTful API server started on: ' + port)
})