refactor(server/notes): Implement singleton architecture

Also trying something out with the response structure on the server to cut down on redundant calls.
This commit is contained in:
Taso committed 2021-04-19 14:14:25 -04:00
1 parent 0f8923058f
commit feb9e8a5d3
8 files changed
+219 -136

No files matched your search

+1 -3
View File
@@ -34,9 +34,7 @@ export const NoteModal = () => {
const handleDeleteNote = () => {
const id = detail.id;
Nui.send(NotesEvents.DELETE_NOTE, {
id,
});
Nui.send(NotesEvents.DELETE_NOTE, id);
setDetail(null);
};
+25 -23
View File
@@ -1,4 +1,4 @@
import { NotesEvents } from '../../typings/notes';
import { Note, NoteServerResponse, NotesEvents } from '../../typings/notes';
import { sendNotesEvent } from '../utils/messages';
onNet(NotesEvents.SEND_NOTE, (notes: any) => {
@@ -6,34 +6,36 @@ onNet(NotesEvents.SEND_NOTE, (notes: any) => {
});
RegisterNuiCallbackType(NotesEvents.ADD_NOTE);
on(`__cfx_nui:${NotesEvents.ADD_NOTE}`, (data: any) => {
emitNet(NotesEvents.ADD_NOTE, data);
});
onNet(NotesEvents.SEND_NOTE_SUCCESS, () => {
emitNet(NotesEvents.FETCH_ALL_NOTES);
});
onNet(NotesEvents.DELETE_NOTE_SUCCESS, () => {
emitNet(NotesEvents.FETCH_ALL_NOTES);
on(`__cfx_nui:${NotesEvents.ADD_NOTE}`, (note: Note) => {
emitNet(NotesEvents.ADD_NOTE, note);
});
RegisterNuiCallbackType(NotesEvents.DELETE_NOTE);
on(`__cfx_nui:${NotesEvents.DELETE_NOTE}`, (data: any) => {
emitNet(NotesEvents.DELETE_NOTE, data);
emitNet(NotesEvents.FETCH_ALL_NOTES);
on(`__cfx_nui:${NotesEvents.DELETE_NOTE}`, (noteId: number) => {
emitNet(NotesEvents.DELETE_NOTE, noteId);
});
RegisterNuiCallbackType(NotesEvents.UPDATE_NOTE);
on(`__cfx_nui:${NotesEvents.UPDATE_NOTE}`, (data: any) => {
emitNet(NotesEvents.UPDATE_NOTE, data);
on(`__cfx_nui:${NotesEvents.UPDATE_NOTE}`, (note: Note) => {
emitNet(NotesEvents.UPDATE_NOTE, note);
});
onNet(NotesEvents.UPDATE_NOTE_SUCCESS, () => {
emitNet(NotesEvents.FETCH_ALL_NOTES);
});
// Trying out this response structure
onNet(
NotesEvents.SERVER_RESP,
({ alert, action, suceeded, refetch, data }: NoteServerResponse<Note[] | Note>) => {
if (alert) {
sendNotesEvent(NotesEvents.SEND_ALERT, alert);
}
onNet(NotesEvents.ACTION_RESULT, (alert: any) => {
sendNotesEvent(NotesEvents.SEND_ALERT, alert);
});
switch (action) {
case 'SEND':
sendNotesEvent(NotesEvents.SEND_NOTE, data);
break;
}
if (refetch && suceeded) {
emitNet(NotesEvents.FETCH_ALL_NOTES);
}
},
);
@@ -0,0 +1,32 @@
import { Note, NotesEvents } from '../../../typings/notes';
import { getSource } from '../utils/miscUtils';
import NotesService from './notes.service';
import { notesLogger } from './notes.utils';
onNet(NotesEvents.ADD_NOTE, (note: Note) => {
const src = getSource();
NotesService.handleAddNote(src, note).catch((e) =>
notesLogger.error(`Error occured in add note event (${src}), Error: ${e.message}`),
);
});
onNet(NotesEvents.FETCH_ALL_NOTES, async (limit?: number) => {
const src = getSource();
NotesService.handleFetchNotes(src, limit).catch((e) =>
notesLogger.error(`Error occured in fetch note event (${src}), Error: ${e.message}`),
);
});
onNet(NotesEvents.DELETE_NOTE, async (noteId: number) => {
const src = getSource();
NotesService.handleDeleteNote(src, noteId).catch((e) =>
notesLogger.error(`Error occured in delete note event (${src}), Error: ${e.message}`),
);
});
onNet(NotesEvents.UPDATE_NOTE, async (note: Note) => {
const src = getSource();
NotesService.handleUpdateNote(src, note).catch((e) =>
notesLogger.error(`Error occured in fetch note event (${src}), Error: ${e.message}`),
);
});
+33
View File
@@ -0,0 +1,33 @@
import { Note } from '../../../typings/notes';
import { pool } from '../db';
import { FetchDefaultLimits } from '../utils/ServerConstants';
export class _NotesDB {
async addNote(identifier: string, note: Note): Promise<void> {
const query = 'INSERT INTO npwd_notes (identifier, title, content) VALUES (?, ?, ?)';
await pool.query(query, [identifier, note.title, note.content]);
}
async fetchNotes(
identifier: string,
limit = FetchDefaultLimits.NOTES_FETCH_LIMIT,
): Promise<Note[]> {
const query = 'SELECT * FROM npwd_notes WHERE identifier = ? ORDER BY id DESC LIMIT ?';
const [result] = await pool.query(query, [identifier, limit]);
return <Note[]>result;
}
async deleteNote(noteId: number, identifier: string): Promise<void> {
const query = 'DELETE FROM npwd_notes WHERE id = ? AND identifier = ?';
await pool.query(query, [noteId, identifier]);
}
async updateNote(note: Note, identifier: string): Promise<void> {
const query = 'UPDATE npwd_notes SET title = ?, content = ? WHERE id = ? AND identifier = ?';
await pool.query(query, [note.title, note.content, note.id, identifier]);
}
}
const NotesDB = new _NotesDB();
export default NotesDB;
+114
View File
@@ -0,0 +1,114 @@
import { Note, NotesEvents, NoteServerResponse } from '../../../typings/notes';
import PlayerService from '../players/player.service';
import NotesDB, { _NotesDB } from './notes.db';
import { notesLogger } from './notes.utils';
class _NotesService {
private readonly notesDB: _NotesDB;
constructor() {
this.notesDB = NotesDB;
}
async handleAddNote(src: number, note: Note): Promise<void> {
notesLogger.debug('Handling add note, note:');
notesLogger.debug(note);
const identifer = PlayerService.getIdentifier(src);
try {
await this.notesDB.addNote(identifer, note);
const serverRespObj: NoteServerResponse = {
action: 'ADD',
suceeded: true,
refetch: true,
alert: {
message: 'NOTES_ADD_SUCCESS',
type: 'success',
},
};
emitNet(NotesEvents.SERVER_RESP, src, serverRespObj);
} catch (e) {
notesLogger.error(`Error in handleAddNote, ${e.message}`);
const serverRespObj: NoteServerResponse = {
action: 'ADD',
suceeded: false,
alert: {
message: 'NOTES_ADD_FAILED',
type: 'success',
},
};
emitNet(NotesEvents.SERVER_RESP, src, serverRespObj);
}
}
async handleFetchNotes(src: number, limit?: number) {
const identifier = PlayerService.getIdentifier(src);
try {
const notes = await this.notesDB.fetchNotes(identifier, limit);
const serverRespObj: NoteServerResponse = {
action: 'SEND',
suceeded: false,
data: notes,
refetch: false,
};
emitNet(NotesEvents.SEND_NOTE, src, serverRespObj);
} catch (e) {
notesLogger.error(`Error in handleFetchNote, ${e.message}`);
}
}
async handleUpdateNote(src: number, note: Note) {
const identifier = PlayerService.getIdentifier(src);
try {
await this.notesDB.updateNote(note, identifier);
const serverRespObj: NoteServerResponse = {
action: 'UPDATE',
suceeded: true,
refetch: true,
};
} catch (e) {
notesLogger.error(`Error in handleUpdateNote, ${e.message}`);
}
}
async handleShareNote(src: number) {
// To implement someday
}
async handleDeleteNote(src: number, noteId: number) {
const identifier = PlayerService.getIdentifier(src);
try {
await this.notesDB.deleteNote(noteId, identifier);
const serverRespObj: NoteServerResponse = {
action: 'DELETE',
suceeded: true,
refetch: true,
alert: {
message: 'NOTES_DELETE_SUCCESS',
type: 'success',
},
};
emitNet(NotesEvents.DELETE_NOTE, src, serverRespObj);
} catch (e) {
notesLogger.error(`Error in handleDeleteNote, ${e.message}`);
const serverRespObj: NoteServerResponse = {
action: 'DELETE',
suceeded: false,
alert: {
message: 'NOTES_DELETE_FAILED',
type: 'error',
},
};
emitNet(NotesEvents.DELETE_NOTE, src, serverRespObj);
}
}
}
const NotesService = new _NotesService();
export default NotesService;
+3
View File
@@ -0,0 +1,3 @@
import { mainLogger } from '../sv_logger';
export const notesLogger = mainLogger.child({ module: 'notes' });
-106
View File
@@ -1,106 +0,0 @@
import { pool } from './db';
import { getIdentifier, getSource } from './functions';
import { Note, NoteId, NotesEvents } from '../../typings/notes';
import { mainLogger } from './sv_logger';
const notesLogger = mainLogger.child({ module: 'notes' });
async function addNote(identifier: string, note: Note): Promise<any> {
const query = 'INSERT INTO npwd_notes (identifier, title, content) VALUES (?, ?, ?)';
await pool.query(query, [identifier, note.title, note.content]);
}
async function fetchAllNotes(identifier: string): Promise<Note[]> {
const query = 'SELECT * FROM npwd_notes WHERE identifier = ? ORDER BY id DESC';
const [result] = await pool.query(query, [identifier]);
return <Note[]>result;
}
async function deleteNote(noteId: number, identifier: string) {
const query = 'DELETE FROM npwd_notes WHERE id = ? AND identifier = ?';
await pool.query(query, [noteId, identifier]);
}
async function updateNote(note: Note, identifier: string): Promise<any> {
const query = 'UPDATE npwd_notes SET title = ?, content = ? WHERE id = ? AND identifier = ?';
await pool.query(query, [note.title, note.content, note.id, identifier]);
}
onNet(NotesEvents.ADD_NOTE, async (note: Note) => {
const pSource = getSource();
try {
const _identifier = getIdentifier(pSource);
await addNote(_identifier, note);
emitNet(NotesEvents.SEND_NOTE_SUCCESS, pSource);
emitNet(NotesEvents.ACTION_RESULT, pSource, {
message: 'NOTES_ADD_SUCCESS',
type: 'success',
});
} catch (e) {
notesLogger.error(`Failed to add note ${e.message}`, {
source: pSource,
});
emitNet(NotesEvents.ACTION_RESULT, pSource, {
message: 'NOTES_ADD_FAILED',
type: 'error',
});
}
});
onNet(NotesEvents.FETCH_ALL_NOTES, async () => {
const pSource = getSource();
try {
const _identifier = getIdentifier(pSource);
const notes = await fetchAllNotes(_identifier);
emitNet(NotesEvents.SEND_NOTE, pSource, notes);
} catch (e) {
notesLogger.error(`Failed to fetch notes ${e.message}`, {
source: pSource,
});
}
});
onNet(NotesEvents.DELETE_NOTE, async (noteId: NoteId) => {
const pSource = getSource();
try {
const _identifier = getIdentifier(pSource);
await deleteNote(noteId.id, _identifier);
emitNet(NotesEvents.DELETE_NOTE_SUCCESS, pSource);
emitNet(NotesEvents.ACTION_RESULT, pSource, {
message: 'NOTES_DELETE_SUCCESS',
type: 'success',
});
} catch (e) {
const pSource = (global as any).source;
notesLogger.error(`Failed to delete note, ${e.message}`);
emitNet(NotesEvents.ACTION_RESULT, pSource, {
message: 'NOTES_DELETE_FAILED',
type: 'error',
});
}
});
onNet(NotesEvents.UPDATE_NOTE, async (note: Note) => {
const pSource = getSource();
try {
const _identifier = getIdentifier(pSource);
await updateNote(note, _identifier);
emitNet(NotesEvents.UPDATE_NOTE_SUCCESS, pSource);
emitNet(NotesEvents.ACTION_RESULT, pSource, {
message: 'NOTES_UPDATE_SUCCESS',
type: 'success',
});
} catch (e) {
emitNet(NotesEvents.UPDATE_NOTE_FAILURE, pSource);
notesLogger.error(`Failed to update note, ${e.message}`, {
source: pSource,
});
emitNet(NotesEvents.ACTION_RESULT, pSource, {
message: 'NOTES_UPDATE_FAILED',
type: 'error',
});
}
});
+11 -4
View File
@@ -1,3 +1,5 @@
import { IAlertProps } from './alerts';
export type AlertCategory =
| 'NOTES_ADD_SUCCESS'
| 'NOTES_ADD_FAILED'
@@ -17,10 +19,6 @@ export interface Note {
content: string;
}
export interface NoteId {
id: number;
}
export enum NotesEvents {
ADD_NOTE = 'npwd:addNote',
FETCH_ALL_NOTES = 'npwd:fetchAllNotes',
@@ -33,4 +31,13 @@ export enum NotesEvents {
UPDATE_NOTE_FAILURE = 'npwd:updateNoteFailure',
ACTION_RESULT = 'npwd:notesActionResult',
SEND_ALERT = 'npwd:notesSetAlert',
SERVER_RESP = 'npwd:notesServerResp',
}
export interface NoteServerResponse<T = unknown> {
alert?: IAlertProps;
action: 'SEND' | 'UPDATE' | 'DELETE' | 'ADD';
suceeded: boolean;
refetch?: boolean;
data?: T;
}