-
Notifications
You must be signed in to change notification settings - Fork 0
/
mod.ts
107 lines (99 loc) · 2.58 KB
/
mod.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
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
import {
Database,
MongoClient,
NextFunction,
Opine,
OpineRequest,
OpineResponse,
} from './deps.ts';
import { appconfig, applogger, errorlogger } from './container.ts';
import { UserRepository } from './lib/mongo/repo/user.repository.ts';
import { LinkRepository } from './lib/mongo/repo/link.repository.ts';
import indexRouter from './routes/index.ts';
import usersRouter from './routes/users.ts';
import linkRouter from './routes/links.ts';
import app from './app.ts';
function _init(app: Opine): void {
new MongoClient()
.connect({
db: Deno.env.get('DB_NAME') as string,
tls: true,
servers: [
{
host: 'nodeclusterbased-shard-00-01.cpkfe.mongodb.net',
port: 27017,
},
{
host: 'nodeclusterbased-shard-00-02.cpkfe.mongodb.net',
port: 27017,
},
{
host: 'nodeclusterbased-shard-00-00.cpkfe.mongodb.net',
port: 27017,
},
],
credential: {
username: (Deno.env.get('DB_USER') as string) || 'AstraVilla',
password: Deno.env.get('DB_PASSWORD') as string,
db: Deno.env.get('DB_NAME') as string,
mechanism: 'SCRAM-SHA-1',
},
})
.then(async (database: Database) => {
applogger.info(
`Connected database to [${appconfig.mongoServerUrl}]`,
);
const userDb = new UserRepository(database, 'users');
const linkDb = new LinkRepository(database, 'links');
await linkDb.createIndexes({
indexes: [{
key: { shortId: 1 },
name: 'short_id_idx',
unique: true,
}],
comment: { userId: 'shortId for fast location of links' },
});
// Mount routers
app.use('/', indexRouter(linkDb));
app.use('/users', usersRouter(userDb));
app.use('/links', linkRouter(userDb, linkDb));
app.use(errorHandler);
// Start our Opine server on the provided or default port.
const server = app.listen(
app.get('port'),
() =>
applogger.info(
`Server ⛳ listening on port ${app.get('port')}`,
),
);
Deno.addSignalListener(
'SIGINT',
() => {
applogger.info(
'🚩 Shutting server gracefully after 3000ms ...!',
);
server.close();
setTimeout(() => {}, 3000);
Deno.exit();
},
);
})
.catch((err: any) => {
errorlogger.error(`Error:[${JSON.stringify(err)}]`);
throw err;
});
}
function errorHandler(
err: any,
_req: OpineRequest,
res: OpineResponse,
_next: NextFunction,
) {
// respond with custom 500 "Internal Server Error".
res.setStatus(500);
res.json({ message: 'Internal Server Error', error: err.message });
}
if (import.meta.main) {
applogger.info(`🧧 Running application from ${Deno.mainModule} ...`);
_init(app);
}