forked from overmind-xyz/over-network-pt-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
storage.ts
49 lines (36 loc) · 1.12 KB
/
storage.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 {
AuthType,
User,
} from './types';
import { promises as fs } from 'fs';
import { stripUsername } from './utils';
const AUTH_FILE = '../app/storage/auth.json';
export async function getUsers() {
const fileContents = await fs.readFile(AUTH_FILE, 'utf8');
const users: AuthType = JSON.parse(fileContents);
return users;
}
export async function storeUser(user: Omit<User, 'followers' | 'following'>) {
if (await getNumberOfUsers() >= 2) {
throw new Error('Max number of users reached');
}
const existing = await getUsers();
if (existing[stripUsername(user.username)]) {
throw new Error('User already exists');
}
await fs.writeFile(
AUTH_FILE,
JSON.stringify(
Object.assign({}, existing, { [stripUsername(user.username)]: user })
)
);
}
export async function dropUser(user: Omit<User, 'followers' | 'following'>) {
const existing = await getUsers();
delete existing[stripUsername(user.username)];
await fs.writeFile(AUTH_FILE, JSON.stringify(existing));
}
export async function getNumberOfUsers() {
const users = await getUsers();
return Object.keys(users).length;
}