-
Notifications
You must be signed in to change notification settings - Fork 86
/
server.js
92 lines (81 loc) · 2.99 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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const dev = process.env.NODE_ENV !== 'production'
if (dev) {
require('dotenv').config()
}
const next = require('next')
const routes = require('./routes')
const mongo = require('mongojs')
const helmet = require('helmet')
const requestCountry = require('request-country')
const config = require('./config')
const validMongoId = require('./lib/valid-mongoid')
const { join } = require('path')
const i18nextMiddleware = require('i18next-express-middleware')
const Backend = require('i18next-node-fs-backend')
const i18n = require('./i18n')
const app = next({ dev })
const handler = routes.getRequestHandler(app)
const port = parseInt(process.env.PORT, 10) || 3000
const express = require('express')
i18n
.use(Backend)
.use(i18nextMiddleware.LanguageDetector)
.init(
{
fallbackLng: 'en',
preload: ['en', 'es', 'no'], // Preload all languages
ns: ['common', 'home'], // Need to preload all the namespaces
backend: {
loadPath: join(__dirname, '/locales/{{lng}}/{{ns}}.json'),
addPath: join(__dirname, '/locales/{{lng}}/{{ns}}.missing.json')
}
},
() => {
// Loaded translations we can bootstrap our routes
app.prepare().then(() => {
const server = express()
const db = mongo(config.DB_CONNECTION)
const collection = db.collection(config.DB_COLLECTION)
server.use(helmet())
server.use(express.json())
server.use(i18nextMiddleware.handle(i18n)) // Enable middleware for i18next
server.use('/locales', express.static(join(__dirname, '/locales'))) // Serve locales for client
server.use(requestCountry.middleware({
privateIpCountry: 'en'
}))
server.get('/sitemap.xml', (req, res) => {
const filePath = join(__dirname, 'static', 'sitemap.xml')
return app.serveStatic(req, res, filePath)
})
server.get('/service-worker.js', (req, res) => {
const filePath = join(__dirname, '.next', 'service-worker.js')
return app.serveStatic(req, res, filePath)
})
server.get('/api/login', (req, res) => {
res.redirect('/')
})
server.get('/api/get/:id', (req, res) => {
const id = req.params && req.params.id ? req.params.id : false
if (!id || !validMongoId(id)) throw new Error('Not a valid id')
collection.findOne({ _id: mongo.ObjectId(id) }, (error, data) => {
if (error) throw error
res.send(data)
})
})
server.post('/locales/add/:lng/:ns', i18nextMiddleware.missingKeyHandler(i18n))
server.post('/api/save', (req, res) => {
const payload = req.body
console.log(payload)
collection.insert(payload, (error, data) => {
if (error) throw error
res.send(data)
})
})
server.use(handler)
server.listen(port, (err) => {
if (err) throw err
console.log(`> Ready on http://localhost:${port}`)
})
})
}
)