-
Notifications
You must be signed in to change notification settings - Fork 20
/
app.js
87 lines (73 loc) · 1.88 KB
/
app.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
const cors = require("cors")
const express = require("express")
const morgan = require("morgan")
const { readFileSync } = require("fs")
const maxmind = require("maxmind")
const { file } = require("./dbInit")
const lookup = new maxmind.Reader(readFileSync(file), {
watchForUpdates: true,
watchForUpdatesHook: () => {
console.log("Database updated")
},
})
const findCountry = (ip) => {
const location = lookup.get(ip)
if (location && location.country) {
return location.country.iso_code
}
}
const app = express()
app.use(
morgan("combined", { skip: (req, res) => process.env.NODE_ENV === "test" }),
)
app.enable("trust proxy")
app.use(cors())
app.enable("etag")
app.use((req, res, next) => {
if (req.path == "/") {
res.set("Cache-Control", "no-cache")
} else {
res.set("Cache-Control", "public, max-age=3600")
}
next()
})
app.use(express.static("public"))
app.get("/info", (req, res) => {
const dataSources = ["maxmind"]
if (req.headers["cf-ipcountry"] !== undefined) {
dataSources.push("cloudflare")
}
res.json({
dataSources,
lastUpdated: lookup.metadata.buildEpoch.toISOString(),
})
})
app.get("/:ip?", (req, res) => {
let country
const ip = req.params.ip || req.ip
if (req.params.ip) {
if (!maxmind.validate(ip)) {
return res
.status(422)
.json({ error: { code: 422, message: "Unprocessable Entity" } })
}
} else {
if (req.headers["cf-ipcountry"] && req.headers["cf-ipcountry"] != "XX") {
country = req.headers["cf-ipcountry"]
}
}
if (!country) {
country = findCountry(ip)
}
if (country) {
res.json({ ip: ip, country: country })
} else {
res.status(404).json({ error: { code: 404, message: "Not Found" } })
}
})
app.get("*", function (req, res) {
return res
.status(422)
.json({ error: { code: 422, message: "Unprocessable Entity" } })
})
module.exports = app