initial commit
[browser-rts.git] / src / repository / session.ts
1 import { v4 as uuid } from 'uuid';
2 import { ERROR_CODE, NotFoundError } from '../errors';
3 import {Repository} from './base';
4
5 export type Session = {
6     id: string;
7     account_id: string;
8 }
9
10 export class SessionRepository extends Repository<Session> {
11     constructor() {
12         super('sessions');
13     }
14
15     async create(accountId: string): Promise<Session>{
16         const data = {
17             id: uuid(),
18             account_id: accountId
19         };
20
21         await this.Delete({
22             account_id: accountId
23         });
24
25         await this.Insert(data);
26
27         return data;
28     }
29
30     async validate(accountId: string, token: string): Promise<Session> {
31         const data = {
32             id: token,
33             account_id: accountId
34         }
35
36         const session = await this.FindOne(data);
37         if(!session) {
38             throw new NotFoundError('Session Invalid', ERROR_CODE.INVALID_USER_TOKEN);
39         }
40
41         return session;
42     }
43 }