-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.ts
49 lines (40 loc) · 1.38 KB
/
db.ts
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
import mongoose from "mongoose"
export const {
MONGODB_CONNECTION_STRING,
MONGODB_PROTOCOL = "mongodb",
MONGODB_USERNAME,
MONGODB_PASSWORD,
MONGODB_HOST = "localhost",
MONGODB_PORT,
MONGODB_DB = "nenkyuu_calendar",
MONGODB_OPTIONS = "",
} = process.env
const mongodbPort = MONGODB_PORT ? `:${MONGODB_PORT}` : ""
const connectionString =
MONGODB_CONNECTION_STRING ||
(MONGODB_USERNAME && MONGODB_PASSWORD
? `${MONGODB_PROTOCOL}://${MONGODB_USERNAME}:${MONGODB_PASSWORD}@${MONGODB_HOST}${mongodbPort}/${MONGODB_DB}${MONGODB_OPTIONS}`
: `${MONGODB_PROTOCOL}://${MONGODB_HOST}${mongodbPort}/${MONGODB_DB}${MONGODB_OPTIONS}`)
export const redactedConnectionString = connectionString.replace(
/:.*@/,
"://***:***@"
)
const mongodb_options = {
useUnifiedTopology: true,
useNewUrlParser: true,
}
mongoose.set("useCreateIndex", true)
export const connect = () => {
console.log(`[MongoDB] Attempting connection to ${redactedConnectionString}`)
mongoose
.connect(connectionString, mongodb_options)
.then(() => {
console.log("[Mongoose] Initial connection successful")
})
.catch((error: Error) => {
console.log("[Mongoose] Initial connection failed, retrying...")
console.error(error)
setTimeout(connect, 5000)
})
}
export const connected = () => mongoose.connection.readyState