-
Notifications
You must be signed in to change notification settings - Fork 185
/
serverBkup.ts
79 lines (67 loc) · 2.04 KB
/
serverBkup.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
import fs from 'fs';
import path from 'path';
import express, { Express, Request, Response, NextFunction } from 'express';
import cors from 'cors';
import bkupEmitter from './pubusb/bkupEmitter';
interface User {
id: number;
firstName: string;
lastName: string;
username: string;
email: string;
}
interface UserRequest extends Request {
users?: User[];
}
const app: Express = express();
const port: number = 8000;
const dataFile = './data/users.json';
const bkupFile = './data/bkup.json'
let users: User[];
fs.readFile(path.resolve(__dirname, dataFile), (err, data) => {
console.log('reading data file ... ');
if (err) throw err;
users = JSON.parse(data.toString());
});
const addMsgToRequest = (req: UserRequest, res: Response, next: NextFunction) => {
if (users) {
req.users = users;
next();
} else {
return res.json({
error: { message: 'users not found', status: 404 }
});
}
};
app.use(cors({ origin: 'http://localhost:3000' }));
app.use('/read/usernames', addMsgToRequest);
app.get('/read/usernames', (req: UserRequest, res: Response) => {
let usernames = req.users?.map((user) => {
return { id: user.id, username: user.username };
});
res.send(usernames);
});
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/write/adduser', addMsgToRequest);
app.post('/write/adduser', (req: UserRequest, res: Response) => {
let newuser = req.body as User;
users.push(newuser);
/**
* Synchronous call to compute the size of the data file
*/
const dataFileSize = fs.statSync(path.resolve(__dirname, dataFile)).size;
if(dataFileSize > 1024) {
bkupEmitter.emit('bkup', users, path.resolve(__dirname, bkupFile)); // emit bkup event when the file size is over 10 Kb
}
else {
fs.writeFile(path.resolve(__dirname, dataFile), JSON.stringify(users), (err) => {
if (err) console.log('Failed to write');
else console.log('User Saved');
});
}
res.send('done');
});
app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});