forked from tobinbradley/dirt-simple-postgis-http-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
147 lines (130 loc) · 4.64 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
const fs = require('fs')
const path = require('path')
require("dotenv").config()
// LOGGER OPTIONS
let logger = false
if ("SERVER_LOGGER" in process.env) {
logger = process.env.SERVER_LOGGER === "true" ? { level: 'info' } : { level: process.env.SERVER_LOGGER }
if ("SERVER_LOGGER_PATH" in process.env) {
logger.file = process.env.SERVER_LOGGER_PATH
}
}
const axios = require("axios");
async function build() {
const fastify = require("fastify")({ logger: logger });
await fastify.register(require('@fastify/express'));
const queryString = require("query-string");
fastify.use((req, res, done) => {
reqParams = req.url.split("?")[1];
const parsedReqParams = queryString.parse(reqParams);
const formId = parsedReqParams.form_id;
tempToken = parsedReqParams.temp_token;
if (formId) {
axios
.get(`${process.env.FORMS_ENDPOINT}${formId}.json`, {
headers: tempToken && tempToken.length > 0 ? {
Authorization: `TempToken ${tempToken}`,
} : {},
})
.then((res) => {
if (res && res.status === 200) {
done();
} else {
done("Forbidden");
}
})
.catch((error) => {
req.log.error(err)
done(error.detail);
});
} else if ("/health-check" == req.url) {
done()
} else {
done("Authentication Failure");
}
});
// EXIT IF POSTGRES_CONNECTION ENV VARIABLE NOT SET
if (!("POSTGRES_CONNECTION" in process.env)) {
throw new Error("Required ENV variable POSTGRES_CONNECTION is not set. Please see README.md for more information.");
}
// POSTGRES CONNECTION
const postgresConfig = { connectionString: process.env.POSTGRES_CONNECTION }
if (process.env.SSL_ROOT_CERT) {
postgresConfig.ssl = {
ca: process.env.SSL_ROOT_CERT
}
} else if (process.env.SSL_ROOT_CERT_PATH) {
postgresConfig.ssl = {
ca: fs.readFileSync(process.env.SSL_ROOT_CERT_PATH).toString()
}
}
fastify.register(require('@fastify/postgres'), postgresConfig)
// COMPRESSION
// add x-protobuf
fastify.register(
require('@fastify/compress'),
{ customTypes: /x-protobuf$/ }
)
// CACHE SETTINGS
fastify.register(
require('@fastify/caching'), {
privacy: process.env.CACHE_PRIVACY || 'private',
expiresIn: process.env.CACHE_EXPIRESIN || 3600,
serverExpiresIn: process.env.CACHE_SERVERCACHE
})
// CORS
fastify.register(require('@fastify/cors'), { origin: typeof process.env.CORS_ORIGIN === 'string' ? process.env.CORS_ORIGINS.split(",") : process.env.CORS_ORIGINS })
// OPTIONAL RATE LIMITER
if ("RATE_MAX" in process.env) {
fastify.register(import('@fastify/rate-limit'), {
max: process.env.RATE_MAX,
timeWindow: '1 minute'
})
}
// INITIALIZE SWAGGER
fastify.register(require('@fastify/swagger'), {
exposeRoute: true,
hideUntagged: true,
swagger: {
"basePath": process.env.BASE_PATH || "/",
"info": {
"title": "Dirt-Simple PostGIS HTTP API",
"description": "The Dirt-Simple PostGIS HTTP API is an easy way to expose geospatial functionality to your applications. It takes simple requests over HTTP and returns JSON, JSONP, or protobuf (Mapbox Vector Tile) to the requester. Although the focus of the project has generally been on exposing PostGIS functionality to web apps, you can use the framework to make an API to any database.",
"version": process.env.npm_package_version || ""
},
"externalDocs": {
"url": "https://github.com/tobinbradley/dirt-simple-postgis-http-api",
"description": "Source code on Github"
},
"tags": [{
"name": "api",
"description": "code related end-points"
}, {
"name": "feature",
"description": "features in common formats for direct mapping."
}, {
"name": "meta",
"description": "meta information for tables and views."
}]
}
})
// ADD ROUTES
fastify.register(require('@fastify/autoload'), {
dir: path.join(__dirname, 'routes')
})
fastify.get('/health-check', { logLevel: 'warn' }, (request, reply) => {
reply.send("healthy");
})
return fastify
}
// LAUNCH SERVER
build()
.then(fastify => // LAUNCH SERVER
fastify.listen({ port: process.env.SERVER_PORT || 3000, host: process.env.SERVER_HOST || '0.0.0.0' }, (err, address) => {
if (err) {
fastify.log.error(err)
process.exit(1)
}
fastify.log.info(`Server listening on ${address}`)
}))
.catch(console.log)