forked from hicommonwealth/commonwealth
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver-test.ts
More file actions
250 lines (221 loc) · 7.34 KB
/
server-test.ts
File metadata and controls
250 lines (221 loc) · 7.34 KB
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
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
/* eslint-disable dot-notation */
import http from 'http';
import favicon from 'serve-favicon';
import logger from 'morgan';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import passport from 'passport';
import session from 'express-session';
import express from 'express';
import SessionSequelizeStore from 'connect-session-sequelize';
import WebSocket from 'ws';
import { SESSION_SECRET, QUERY_URL_OVERRIDE } from './server/config';
import setupAPI from './server/router';
import setupPassport from './server/passport';
import models from './server/database';
import setupWebsocketServer from './server/socket';
import { NotificationCategories } from './shared/types';
import ChainObjectFetcher from './server/util/chainObjectFetcher';
import ViewCountCache from './server/util/viewCountCache';
import { SubstrateEventKinds } from './shared/events/edgeware/types';
require('express-async-errors');
const FETCH_INTERVAL_MS = +process.env.FETCH_INTERVAL_MS || 600000; // default fetch interval is 10min
const app = express();
const SequelizeStore = SessionSequelizeStore(session.Store);
const fetcher = new ChainObjectFetcher(models, FETCH_INTERVAL_MS, QUERY_URL_OVERRIDE);
// set cache TTL to 1 second to test invalidation
const viewCountCache = new ViewCountCache(1, 10 * 60);
const wss = new WebSocket.Server({ clientTracking: false, noServer: true });
let server;
const sessionParser = session({
secret: SESSION_SECRET,
store: new SequelizeStore({
db: models.sequelize,
tableName: 'Sessions',
checkExpirationInterval: 15 * 60 * 1000, // Clean up expired sessions every 15 minutes
expiration: 7 * 24 * 60 * 60 * 1000 // Set session expiration to 7 days
}),
resave: false,
saveUninitialized: true,
});
// serve static files
app.use(favicon(`${__dirname}/favicon.ico`));
app.use('/static', express.static('static'));
// add other middlewares
// app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(sessionParser);
app.use(passport.initialize());
app.use(passport.session());
// store wss into request obj
app.use((req, res, next) => {
req['wss'] = wss;
next();
});
const setupErrorHandlers = () => {
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err : any = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.json({ error: err.message });
});
};
const resetServer = (debug=false): Promise<void> => {
if (debug) console.log('Resetting database...');
return new Promise((resolve) => {
models.sequelize.sync({ force: true }).then(async () => {
if (debug) console.log('Initializing default models...');
const drew = await models['User'].create({
email: 'drewstone329@gmail.com',
emailVerified: true,
isAdmin: true,
lastVisited: '{}',
});
// For all smart contract support chains
await models['ContractCategory'].create({
name: 'Tokens',
description: 'Token related contracts',
color: '#4a90e2',
});
await models['ContractCategory'].create({
name: 'DAOs',
description: 'DAO related contracts',
color: '#9013fe',
});
// Initialize different chain + node URLs
const edgMain = await models['Chain'].create({
id: 'edgeware',
network: 'edgeware',
symbol: 'EDG',
name: 'Edgeware Mainnet',
icon_url: '/static/img/protocols/edg.png',
active: true,
type: 'chain',
});
const eth = await models['Chain'].create({
id: 'ethereum',
network: 'ethereum',
symbol: 'ETH',
name: 'Ethereum',
icon_url: '/static/img/protocols/eth.png',
active: true,
type: 'chain',
});
await models['Address'].create({
user_id: 1,
address: '0x34C3A5ea06a3A67229fb21a7043243B0eB3e853f',
chain: 'ethereum',
selected: true,
verification_token: 'PLACEHOLDER',
verification_token_expires: null,
verified: new Date(),
});
// Notification Categories
await models['NotificationCategory'].create({
name: NotificationCategories.NewCommunity,
description: 'someone makes a new community'
});
await models['NotificationCategory'].create({
name: NotificationCategories.NewThread,
description: 'someone makes a new thread'
});
await models['NotificationCategory'].create({
name: NotificationCategories.NewComment,
description: 'someone makes a new comment',
});
await models['NotificationCategory'].create({
name: NotificationCategories.NewMention,
description: 'someone @ mentions a user',
});
await models['NotificationCategory'].create({
name: NotificationCategories.ChainEvent,
description: 'a chain event occurs',
});
await models['NotificationCategory'].create({
name: NotificationCategories.NewReaction,
description: 'someone reacts to a post',
});
// Admins need to be subscribed to mentions
await models['Subscription'].create({
subscriber_id: drew.id,
category_id: NotificationCategories.NewMention,
object_id: `user-${drew.id}`,
is_active: true,
});
// Communities
await models['OffchainCommunity'].create({
id: 'staking',
name: 'Staking',
creator_id: 1,
description: 'All things staking',
default_chain: 'ethereum',
});
const nodes = [
[ 'mainnet1.edgewa.re', 'edgeware' ],
[ 'wss://mainnet.infura.io/ws', 'ethereum' ],
];
await Promise.all(nodes.map(([ url, chain, address ]) => (models['ChainNode'].create({ chain, url, address }))));
// initialize chain event types
const initChainEventTypes = (chain) => {
return Promise.all(
SubstrateEventKinds.map((event_name) => {
return models['ChainEventType'].create({
id: `${chain}-${event_name}`,
chain,
event_name,
});
})
);
};
await initChainEventTypes('edgeware');
if (debug) console.log('Database reset!');
resolve();
});
});
};
const setupServer = () => {
const port = 8081;
app.set('port', port);
server = http.createServer(app);
const onError = (error) => {
if (error.syscall !== 'listen') {
throw error;
}
switch (error.code) {
case 'EACCES':
console.error('Port requires elevated privileges');
process.exit(1);
break;
case 'EADDRINUSE':
console.error('Port is already in use');
process.exit(1);
break;
default:
throw error;
}
};
const onListen = () => {
const addr = server.address();
if (typeof addr === 'string') {
console.log(`Listening on ${addr}`);
} else {
console.log(`Listening on port ${addr.port}`);
}
};
setupWebsocketServer(wss, server, sessionParser, false);
server.listen(port);
server.on('error', onError);
server.on('listening', onListen);
};
setupPassport(models);
setupAPI(app, models, fetcher, viewCountCache);
setupErrorHandlers();
setupServer();
export const resetDatabase = () => resetServer();
export default app;