diff --git a/phone/src/Phone.tsx b/phone/src/Phone.tsx
index bcdb2c0..0037211 100644
--- a/phone/src/Phone.tsx
+++ b/phone/src/Phone.tsx
@@ -15,7 +15,6 @@ import { useMatchService } from './apps/match/hooks/useMatchService';
import { useMarketplaceService } from './apps/marketplace/hooks/useMarketplaceService';
import { useBankService } from './apps/bank/hooks/useBankService';
import { useMessagesService } from './apps/messages/hooks/useMessageService';
-import { useNotesService } from './apps/notes/hooks/useNotesService';
import { usePhotoService } from './apps/camera/hooks/usePhotoService';
import { isSettingsSchemaValid, useSettings } from './apps/settings/hooks/useSettings';
import { useCallService } from './os/call/hooks/useCallService';
@@ -75,7 +74,6 @@ function Phone() {
useMarketplaceService();
useBankService();
useMessagesService();
- useNotesService();
usePhotoService();
useCallService();
useDialService();
diff --git a/phone/src/apps/notes/NotesApp.tsx b/phone/src/apps/notes/NotesApp.tsx
index ddf5b1c..bd0518e 100644
--- a/phone/src/apps/notes/NotesApp.tsx
+++ b/phone/src/apps/notes/NotesApp.tsx
@@ -7,20 +7,19 @@ import NoteList from './list/NoteList';
import { NoteModal } from './modal/NoteModal';
import { Fab } from '@material-ui/core';
import AddIcon from '@material-ui/icons/Add';
-import { useNoteDetail } from './hooks/useNoteDetail';
import useStyles from './notes.styles';
-import InjectDebugData from '../../os/debug/InjectDebugData';
import { NotesThemeProvider } from './providers/NotesThemeProvider';
import { Route } from 'react-router-dom';
-import { NotesEvents } from '../../../../typings/notes';
+import { useSetSelectedNote } from './hooks/state';
+import { LoadingSpinner } from '../../ui/components/LoadingSpinner';
export const NotesApp = () => {
const classes = useStyles();
const notesApp = useApp('NOTES');
- const { setDetail } = useNoteDetail();
+ const setSelectedNote = useSetSelectedNote();
const onClickCreate = () => {
- setDetail({ title: '', content: '' });
+ setSelectedNote({ title: '', content: '' });
};
return (
@@ -29,7 +28,9 @@ export const NotesApp = () => {
-
+ }>
+
+
@@ -38,22 +39,3 @@ export const NotesApp = () => {
);
};
-
-InjectDebugData([
- {
- app: 'NOTES',
- method: NotesEvents.SEND_NOTE,
- data: [
- {
- id: 1,
- title: 'First note',
- content: 'Hello, this is my shitty note',
- },
- {
- id: 2,
- title: 'Second note',
- content: 'Hello, this is another shitty note',
- },
- ],
- },
-]);
diff --git a/phone/src/apps/notes/hooks/state.ts b/phone/src/apps/notes/hooks/state.ts
index 37c31d5..f0743f7 100644
--- a/phone/src/apps/notes/hooks/state.ts
+++ b/phone/src/apps/notes/hooks/state.ts
@@ -1,16 +1,40 @@
-import { atom } from 'recoil';
+import { atom, selector, useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
+import { fetchNui } from '../../../utils/fetchNui';
+import { ServerPromiseResp } from '../../../../../typings/common';
+import { NoteItem, NotesEvents } from '../../../../../typings/notes';
+import LogDebugEvent from '../../../os/debug/LogDebugEvents';
+import { isEnvBrowser } from '../../../utils/misc';
+import { BrowserNotesData } from '../utils/constants';
export const noteStates = {
noteItems: atom({
key: 'noteItem',
- default: [],
+ default: selector({
+ key: 'defaultNoteItems',
+ get: async () => {
+ try {
+ const resp = await fetchNui>(NotesEvents.FETCH_ALL_NOTES);
+ LogDebugEvent({ action: 'FetchNotes', data: resp.data });
+ return resp.data;
+ } catch (e) {
+ if (isEnvBrowser()) {
+ return BrowserNotesData;
+ }
+ console.error(e);
+ return [];
+ }
+ },
+ }),
}),
- noteModal: atom({
- key: 'noteModal',
- default: false,
- }),
- noteDetail: atom({
- key: 'noteDetail',
+ selectedNote: atom | null>({
+ key: 'selectedNote',
default: null,
}),
};
+
+export const useSetSelectedNote = () => useSetRecoilState(noteStates.selectedNote);
+export const useSelectedNoteValue = () => useRecoilValue(noteStates.selectedNote);
+export const useSelectedNote = () => useRecoilState(noteStates.selectedNote);
+
+export const useNotesValue = () => useRecoilValue(noteStates.noteItems);
+export const useSetNotes = () => useSetRecoilState(noteStates.noteItems);
diff --git a/phone/src/apps/notes/hooks/useNoteDetail.ts b/phone/src/apps/notes/hooks/useNoteDetail.ts
deleted file mode 100644
index 38737ab..0000000
--- a/phone/src/apps/notes/hooks/useNoteDetail.ts
+++ /dev/null
@@ -1,13 +0,0 @@
-import { useRecoilState } from 'recoil';
-import { Note } from '../../../../../typings/notes';
-import { noteStates } from './state';
-
-interface NoteDetailProps {
- detail: Note;
- setDetail: (note: object) => void;
-}
-
-export const useNoteDetail = (): NoteDetailProps => {
- const [detail, setDetail] = useRecoilState(noteStates.noteDetail);
- return { detail, setDetail };
-};
diff --git a/phone/src/apps/notes/hooks/useNotes.ts b/phone/src/apps/notes/hooks/useNotes.ts
deleted file mode 100644
index bced5c1..0000000
--- a/phone/src/apps/notes/hooks/useNotes.ts
+++ /dev/null
@@ -1,12 +0,0 @@
-import { useRecoilValue } from 'recoil';
-import { Note } from '../../../../../typings/notes';
-import { noteStates } from './state';
-
-interface NotesProps {
- notes: Note[];
-}
-
-export const useNotes = (): NotesProps => {
- const notes = useRecoilValue(noteStates.noteItems);
- return { notes };
-};
diff --git a/phone/src/apps/notes/hooks/useNotesActions.ts b/phone/src/apps/notes/hooks/useNotesActions.ts
new file mode 100644
index 0000000..5210311
--- /dev/null
+++ b/phone/src/apps/notes/hooks/useNotesActions.ts
@@ -0,0 +1,41 @@
+import { useSetNotes } from './state';
+import { useCallback } from 'react';
+import { NoteItem } from '../../../../../typings/notes';
+
+interface UseNotesActionsValue {
+ deleteNote: (id: number) => void;
+ addNote: (note: NoteItem) => void;
+ updateNote: (note: NoteItem) => void;
+}
+
+export const useNotesActions = (): UseNotesActionsValue => {
+ const setNotes = useSetNotes();
+
+ const deleteNote = useCallback(
+ (id) => {
+ setNotes((curNotes) => [...curNotes].filter((note) => note.id !== id));
+ },
+ [setNotes],
+ );
+
+ const addNote = useCallback(
+ (note: NoteItem) => {
+ setNotes((curNotes) => [...curNotes, note]);
+ },
+ [setNotes],
+ );
+
+ const updateNote = useCallback(
+ (note: NoteItem) => {
+ setNotes((curNotes) => {
+ const targetIndex = curNotes.findIndex((storedNote) => storedNote.id === note.id);
+ const newNotesArray = [...curNotes];
+ newNotesArray[targetIndex] = note;
+ return newNotesArray;
+ });
+ },
+ [setNotes],
+ );
+
+ return { deleteNote, addNote, updateNote };
+};
diff --git a/phone/src/apps/notes/hooks/useNotesService.ts b/phone/src/apps/notes/hooks/useNotesService.ts
deleted file mode 100644
index a45e011..0000000
--- a/phone/src/apps/notes/hooks/useNotesService.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import { useSetRecoilState } from 'recoil';
-import { useNuiEvent } from 'fivem-nui-react-lib';
-import { noteStates } from './state';
-import { IAlert, useSnackbar } from '../../../ui/hooks/useSnackbar';
-import { useTranslation } from 'react-i18next';
-import { NotesEvents } from '../../../../../typings/notes';
-
-export const useNotesService = () => {
- const { addAlert } = useSnackbar();
- const setNotes = useSetRecoilState(noteStates.noteItems);
- const { t } = useTranslation();
-
- const handleAddAlert = ({ message, type }: IAlert) => {
- addAlert({
- message: t(`APPS_${message}`),
- type,
- });
- };
-
- useNuiEvent('NOTES', NotesEvents.SEND_NOTE, setNotes);
- useNuiEvent('NOTES', NotesEvents.SEND_ALERT, handleAddAlert);
-};
diff --git a/phone/src/apps/notes/list/NoteList.tsx b/phone/src/apps/notes/list/NoteList.tsx
index cfe8259..7daab1a 100644
--- a/phone/src/apps/notes/list/NoteList.tsx
+++ b/phone/src/apps/notes/list/NoteList.tsx
@@ -1,25 +1,51 @@
import React from 'react';
-import { List, ListItem, ListItemText } from '@material-ui/core';
-import { useNoteDetail } from '../hooks/useNoteDetail';
-import { useNotes } from '../hooks/useNotes';
+import { Box, List, ListItem, ListItemText, Typography } from '@material-ui/core';
+import { useNotesValue } from '../hooks/state';
+import { useSetSelectedNote } from '../hooks/state';
+import { NoteItem } from '../../../../../typings/notes';
+import { makeStyles, Theme } from '@material-ui/core/styles';
+import { Notes } from '@material-ui/icons';
+
+const useStyles = makeStyles((theme: Theme) => ({
+ noNotes: {
+ color: theme.palette.text.secondary,
+ },
+}));
// TODO: add search bar later
const NoteList = () => {
- const { notes } = useNotes();
- const { setDetail } = useNoteDetail();
+ const classes = useStyles();
+ const notes = useNotesValue();
+ const setNote = useSetSelectedNote();
- const handleNoteModal = (note) => {
- setDetail(note);
+ const handleNoteModal = (note: NoteItem) => {
+ setNote(note);
};
+ if (notes && notes.length)
+ return (
+
+ {notes.map((note) => (
+ handleNoteModal(note)}>
+ {note.title}
+
+ ))}
+
+ );
+
return (
-
- {notes.map((note) => (
- handleNoteModal(note)}>
- {note.title}
-
- ))}
-
+
+
+ You have no notes
+
+
);
};
diff --git a/phone/src/apps/notes/modal/NoteModal.tsx b/phone/src/apps/notes/modal/NoteModal.tsx
index f102db6..81fb434 100644
--- a/phone/src/apps/notes/modal/NoteModal.tsx
+++ b/phone/src/apps/notes/modal/NoteModal.tsx
@@ -1,128 +1,192 @@
-import {
- Button,
- Slide,
- Paper,
- Typography,
- Container,
- CircularProgress,
- Box,
-} from '@material-ui/core';
-import React from 'react';
+import { Button, Slide, Paper, Typography, Container, Box } from '@material-ui/core';
+import React, { useEffect, useState } from 'react';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
-import { useNoteDetail } from '../hooks/useNoteDetail';
import useStyles from './modal.styles';
-import { useNuiRequest } from 'fivem-nui-react-lib';
import { useTranslation } from 'react-i18next';
import { StatusButton } from '../../../ui/components/StatusButton';
-import { NotesEvents } from '../../../../../typings/notes';
+import { DeleteNoteDTO, NoteItem, NotesEvents } from '../../../../../typings/notes';
import { TextField } from '../../../ui/components/Input';
+import { fetchNui } from '../../../utils/fetchNui';
+import { useSelectedNote } from '../hooks/state';
+import { ServerPromiseResp } from '../../../../../typings/common';
+import { useSnackbar } from '../../../ui/hooks/useSnackbar';
+import { useNotesActions } from '../hooks/useNotesActions';
export const NoteModal = () => {
- const Nui = useNuiRequest();
const classes = useStyles();
+ const { addNote, deleteNote, updateNote } = useNotesActions();
const { t } = useTranslation();
- const { detail, setDetail } = useNoteDetail();
+ const [selectedNote, setSelectedNote] = useSelectedNote();
+ const [noteTitle, setNoteTitle] = useState('');
+ const [noteContent, setNoteContent] = useState('');
+ const { addAlert } = useSnackbar();
- const _handleClose = () => {
- setDetail(null);
- };
+ const isNewNote = !Boolean(selectedNote?.id);
+
+ useEffect(() => {
+ if (selectedNote !== null) {
+ setNoteContent(selectedNote.content);
+ setNoteTitle(selectedNote.title);
+ }
+ }, [selectedNote]);
const handleNoteSave = () => {
- Nui.send(NotesEvents.ADD_NOTE, detail);
- setDetail(null);
+ fetchNui>(NotesEvents.ADD_NOTE, {
+ title: noteTitle,
+ content: noteContent,
+ }).then((resp) => {
+ if (resp.status !== 'ok') {
+ return addAlert({
+ message: t('APPS_NOTES_ADD_FAILED'),
+ type: 'error',
+ });
+ }
+
+ addNote(resp.data);
+
+ addAlert({
+ message: t('APPS_NOTES_ADD_SUCCESS'),
+ type: 'success',
+ });
+ setSelectedNote(null);
+ });
};
const handleDeleteNote = () => {
- const id = detail.id;
- Nui.send(NotesEvents.DELETE_NOTE, id);
- setDetail(null);
+ fetchNui>(NotesEvents.DELETE_NOTE, selectedNote).then(
+ (resp) => {
+ if (resp.status !== 'ok') {
+ return addAlert({
+ message: t('APPS_NOTES_DELETE_FAILED'),
+ type: 'error',
+ });
+ }
+
+ deleteNote(resp.data.id);
+
+ addAlert({
+ message: t('APPS_NOTES_DELETE_SUCCESS'),
+ type: 'success',
+ });
+ },
+ );
+ setSelectedNote(null);
};
const handleUpdateNote = () => {
- Nui.send(NotesEvents.UPDATE_NOTE, detail);
- setDetail(null);
+ fetchNui(NotesEvents.ADD_NOTE, selectedNote).then((resp) => {
+ if (resp.status !== 'ok') {
+ return addAlert({
+ message: t('APPS_NOTES_UPDATE_FAILED'),
+ type: 'error',
+ });
+ }
+
+ updateNote({ id: selectedNote.id, title: noteTitle, content: noteContent });
+
+ addAlert({
+ message: t('APPS_NOTES_UPDATE_SUCCESS'),
+ type: 'success',
+ });
+ });
+ setSelectedNote(null);
};
+ const handleTitleChange = (e: React.ChangeEvent) => {
+ setNoteTitle(e.target.value);
+ };
+
+ const handleContentChange = (e: React.ChangeEvent) => {
+ setNoteContent(e.target.value);
+ };
+
+ const _handleClose = () => {
+ setSelectedNote(null);
+ };
+
+ if (selectedNote === null) return null;
+
return (
-
+
- {!detail ? (
-
- ) : (
-
-
-
- }
- onClick={_handleClose}
- >
- {t('APPS_NOTES')}
-
-
- setDetail((d) => ({ ...d, title: e.target.value }))}
- />
- setDetail((d) => ({ ...d, content: e.target.value }))}
- />
- {detail.content.length}/250
- {!detail.id ? (
- <>
-
-
-
-
-
- {t('GENERIC_CANCEL')}
-
-
- >
- ) : (
- <>
-
-
-
-
-
- {t('GENERIC_DELETE')}
-
-
- >
- )}
+
+
+
+ }
+ onClick={_handleClose}
+ >
+ {t('APPS_NOTES')}
+
-
- )}
+
+
+ {noteContent.length}/250
+ {isNewNote ? (
+ <>
+
+
+
+
+
+ {t('GENERIC_CANCEL')}
+
+
+ >
+ ) : (
+ <>
+
+
+
+
+
+ {t('GENERIC_DELETE')}
+
+
+ >
+ )}
+
+
);
diff --git a/phone/src/apps/notes/utils/constants.ts b/phone/src/apps/notes/utils/constants.ts
new file mode 100644
index 0000000..a07e1b8
--- /dev/null
+++ b/phone/src/apps/notes/utils/constants.ts
@@ -0,0 +1,24 @@
+import { NoteItem } from '../../../../../typings/notes';
+
+export const BrowserNotesData: NoteItem[] = [
+ {
+ id: 1,
+ title: 'You suck',
+ content: 'Nice note bro',
+ },
+ {
+ id: 2,
+ title: 'You suck',
+ content: 'Nice note bro',
+ },
+ {
+ id: 3,
+ title: 'You suck',
+ content: 'Nice note bro',
+ },
+ {
+ id: 4,
+ title: 'You suck',
+ content: 'Nice note bro',
+ },
+];
diff --git a/resources/client/cl_main.ts b/resources/client/cl_main.ts
index c850aec..5105ea9 100644
--- a/resources/client/cl_main.ts
+++ b/resources/client/cl_main.ts
@@ -1,11 +1,8 @@
import { sendMessage } from '../utils/messages';
import { PhoneEvents } from '../../typings/phone';
import { TwitterEvents } from '../../typings/twitter';
-import { ContactEvents } from '../../typings/contact';
-import { MarketplaceEvents } from '../../typings/marketplace';
import { phoneCloseAnim, phoneOpenAnim, removePhoneProp } from './functions';
import { MessageEvents } from '../../typings/messages';
-import { NotesEvents } from '../../typings/notes';
import { BankEvents } from '../../typings/bank';
import { PhotoEvents } from '../../typings/photo';
import { CallEvents } from '../../typings/call';
@@ -19,7 +16,6 @@ let isPhoneOpen = false;
*
* * * * * * * * * * * * */
function fetchOnInitialize() {
- emitNet(ContactEvents.GET_CONTACTS);
emitNet(MessageEvents.FETCH_MESSAGE_GROUPS);
emitNet(TwitterEvents.GET_OR_CREATE_PROFILE);
sendMessage('PHONE', PhoneEvents.SET_CONFIG, config);
@@ -143,11 +139,6 @@ on(`__cfx_nui:${PhoneEvents.UI_IS_READY}`, (_data: any, cb: Function) => {
* NUI Service Callback Registration
*
* * * * * * * * * * * * */
-RegisterNuiCallbackType(PhoneEvents.OPEN_APP_NOTES);
-on(`__cfx_nui:${PhoneEvents.OPEN_APP_NOTES}`, (data: any, cb: Function) => {
- emitNet(NotesEvents.FETCH_ALL_NOTES);
- cb();
-});
RegisterNuiCallbackType(PhoneEvents.OPEN_APP_BANK);
on(`__cfx_nui:${PhoneEvents.OPEN_APP_BANK}`, (data: any, cb: Function) => {
diff --git a/resources/client/cl_notes.ts b/resources/client/cl_notes.ts
index fee013f..8e3746c 100644
--- a/resources/client/cl_notes.ts
+++ b/resources/client/cl_notes.ts
@@ -1,37 +1,7 @@
-import { Note, NotesEvents } from '../../typings/notes';
-import { sendNotesEvent } from '../utils/messages';
+import { NotesEvents } from '../../typings/notes';
+import { RegisterNuiProxy } from './cl_utils';
-onNet(NotesEvents.SEND_NOTE, (notes: any) => {
- sendNotesEvent(NotesEvents.SEND_NOTE, notes);
-});
-
-RegisterNuiCallbackType(NotesEvents.ADD_NOTE);
-on(`__cfx_nui:${NotesEvents.ADD_NOTE}`, (note: Note) => {
- emitNet(NotesEvents.ADD_NOTE, note);
-});
-
-RegisterNuiCallbackType(NotesEvents.DELETE_NOTE);
-on(`__cfx_nui:${NotesEvents.DELETE_NOTE}`, (noteId: number) => {
- emitNet(NotesEvents.DELETE_NOTE, noteId);
-});
-
-RegisterNuiCallbackType(NotesEvents.UPDATE_NOTE);
-on(`__cfx_nui:${NotesEvents.UPDATE_NOTE}`, (note: Note) => {
- emitNet(NotesEvents.UPDATE_NOTE, note);
-});
-
-onNet(NotesEvents.SEND_NOTE_SUCCESS, () => {
- emitNet(NotesEvents.FETCH_ALL_NOTES);
-});
-
-onNet(NotesEvents.UPDATE_NOTE_SUCCESS, () => {
- emitNet(NotesEvents.FETCH_ALL_NOTES);
-});
-
-onNet(NotesEvents.ACTION_RESULT, (alert: any) => {
- sendNotesEvent(NotesEvents.SEND_ALERT, alert);
-});
-
-onNet(NotesEvents.DELETE_NOTE_SUCCESS, () => {
- emitNet(NotesEvents.FETCH_ALL_NOTES);
-});
+RegisterNuiProxy(NotesEvents.ADD_NOTE);
+RegisterNuiProxy(NotesEvents.FETCH_ALL_NOTES);
+RegisterNuiProxy(NotesEvents.UPDATE_NOTE);
+RegisterNuiProxy(NotesEvents.DELETE_NOTE);
diff --git a/resources/server/notes/notes.controller.ts b/resources/server/notes/notes.controller.ts
index 23bea79..a57fb11 100644
--- a/resources/server/notes/notes.controller.ts
+++ b/resources/server/notes/notes.controller.ts
@@ -1,32 +1,36 @@
-import { Note, NotesEvents } from '../../../typings/notes';
-import { getSource } from '../utils/miscUtils';
+import { BeforeDBNote, DeleteNoteDTO, NoteItem, NotesEvents } from '../../../typings/notes';
import NotesService from './notes.service';
import { notesLogger } from './notes.utils';
+import { onNetPromise } from '../utils/PromiseNetEvents/onNetPromise';
-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}`),
- );
+onNetPromise(NotesEvents.ADD_NOTE, (reqObj, resp) => {
+ NotesService.handleAddNote(reqObj, resp).catch((e) => {
+ notesLogger.error(`Error occured in add note event (${reqObj.source}), Error: ${e.message}`);
+ resp({ status: 'error', errorMsg: 'UNKNOWN_ERROR' });
+ });
});
-onNet(NotesEvents.FETCH_ALL_NOTES, async (limit?: number) => {
- const src = getSource();
- NotesService.handleFetchNotes(src, limit).catch((e) =>
- notesLogger.error(`Error occurred in fetch note event (${src}), Error: ${e.message}`),
- );
+onNetPromise(NotesEvents.FETCH_ALL_NOTES, (reqObj, resp) => {
+ NotesService.handleFetchNotes(reqObj, resp).catch((e) => {
+ notesLogger.error(
+ `Error occurred in fetch note event (${reqObj.source}), Error: ${e.message}`,
+ );
+ resp({ status: 'error', errorMsg: 'UNKNOWN_ERROR' });
+ });
});
-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}`),
- );
+onNetPromise(NotesEvents.DELETE_NOTE, async (reqObj, resp) => {
+ NotesService.handleDeleteNote(reqObj, resp).catch((e) => {
+ notesLogger.error(
+ `Error occured in delete note event (${reqObj.source}), Error: ${e.message}`,
+ );
+ resp({ status: 'error', errorMsg: 'UNKNOWN_ERROR' });
+ });
});
-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}`),
- );
+onNetPromise(NotesEvents.UPDATE_NOTE, async (reqObj, resp) => {
+ NotesService.handleUpdateNote(reqObj, resp).catch((e) => {
+ notesLogger.error(`Error occured in fetch note event (${reqObj.source}), Error: ${e.message}`);
+ resp({ status: 'error', errorMsg: 'UNKNOWN_ERROR' });
+ });
});
diff --git a/resources/server/notes/notes.db.ts b/resources/server/notes/notes.db.ts
index 1e6a0a9..b3d9c0e 100644
--- a/resources/server/notes/notes.db.ts
+++ b/resources/server/notes/notes.db.ts
@@ -1,20 +1,19 @@
-import { Note } from '../../../typings/notes';
+import { BeforeDBNote, NoteItem } from '../../../typings/notes';
import { pool } from '../db';
import { FetchDefaultLimits } from '../utils/ServerConstants';
+import { ResultSetHeader } from 'mysql2';
export class _NotesDB {
- async addNote(identifier: string, note: Note): Promise {
+ async addNote(identifier: string, note: BeforeDBNote): Promise {
const query = 'INSERT INTO npwd_notes (identifier, title, content) VALUES (?, ?, ?)';
- await pool.query(query, [identifier, note.title, note.content]);
+ const [result] = await pool.query(query, [identifier, note.title, note.content]);
+ return (result).insertId;
}
- async fetchNotes(
- identifier: string,
- limit = FetchDefaultLimits.NOTES_FETCH_LIMIT,
- ): Promise {
- const query = 'SELECT * FROM npwd_notes WHERE identifier = ? ORDER BY id DESC LIMIT ?';
- const [result] = await pool.query(query, [identifier, limit]);
- return result;
+ async fetchNotes(identifier: string): Promise {
+ const query = 'SELECT * FROM npwd_notes WHERE identifier = ? ORDER BY id DESC';
+ const [result] = await pool.query(query, [identifier]);
+ return result;
}
async deleteNote(noteId: number, identifier: string): Promise {
@@ -22,7 +21,7 @@ export class _NotesDB {
await pool.query(query, [noteId, identifier]);
}
- async updateNote(note: Note, identifier: string): Promise {
+ async updateNote(note: NoteItem, identifier: string): Promise {
const query = 'UPDATE npwd_notes SET title = ?, content = ? WHERE id = ? AND identifier = ?';
await pool.query(query, [note.title, note.content, note.id, identifier]);
}
diff --git a/resources/server/notes/notes.service.ts b/resources/server/notes/notes.service.ts
index 4cb4929..ac34c9c 100644
--- a/resources/server/notes/notes.service.ts
+++ b/resources/server/notes/notes.service.ts
@@ -1,7 +1,8 @@
-import { Note, NotesEvents } from '../../../typings/notes';
+import { BeforeDBNote, DeleteNoteDTO, NoteItem } from '../../../typings/notes';
import PlayerService from '../players/player.service';
import NotesDB, { _NotesDB } from './notes.db';
import { notesLogger } from './notes.utils';
+import { PromiseEventResp, PromiseRequest } from '../utils/PromiseNetEvents/promise.types';
class _NotesService {
private readonly notesDB: _NotesDB;
@@ -11,57 +12,47 @@ class _NotesService {
notesLogger.debug('Notes service started');
}
- async handleAddNote(src: number, note: Note): Promise {
+ async handleAddNote(
+ reqObj: PromiseRequest,
+ resp: PromiseEventResp,
+ ): Promise {
notesLogger.debug('Handling add note, note:');
- notesLogger.debug(note);
+ notesLogger.debug(reqObj.data);
- const identifer = PlayerService.getIdentifier(src);
+ const identifer = PlayerService.getIdentifier(reqObj.source);
try {
- await this.notesDB.addNote(identifer, note);
-
- emitNet(NotesEvents.SEND_NOTE_SUCCESS, src);
- emitNet(NotesEvents.ACTION_RESULT, src, {
- message: 'NOTES_ADD_SUCCESS',
- type: 'success',
+ const noteId = await this.notesDB.addNote(identifer, reqObj.data);
+ resp({
+ status: 'ok',
+ data: { id: noteId, content: reqObj.data.content, title: reqObj.data.title },
});
} catch (e) {
notesLogger.error(`Error in handleAddNote, ${e.message}`);
- emitNet(NotesEvents.ACTION_RESULT, src, {
- message: 'NOTES_ADD_FAILED',
- type: 'error',
- });
+ resp({ status: 'error', errorMsg: 'DB_ERROR' });
}
}
- async handleFetchNotes(src: number, limit?: number) {
- const identifier = PlayerService.getIdentifier(src);
+ async handleFetchNotes(reqObj: PromiseRequest, resp: PromiseEventResp) {
+ const identifier = PlayerService.getIdentifier(reqObj.source);
try {
- const notes = await this.notesDB.fetchNotes(identifier, limit);
- emitNet(NotesEvents.SEND_NOTE, src, notes);
+ const notes = await this.notesDB.fetchNotes(identifier);
+ resp({ status: 'ok', data: notes });
} catch (e) {
notesLogger.error(`Error in handleFetchNote, ${e.message}`);
+ resp({ status: 'error', errorMsg: 'DB_ERROR' });
}
}
- async handleUpdateNote(src: number, note: Note) {
- const identifier = PlayerService.getIdentifier(src);
+ async handleUpdateNote(reqObj: PromiseRequest, resp: PromiseEventResp) {
+ const identifier = PlayerService.getIdentifier(reqObj.source);
try {
- await this.notesDB.updateNote(note, identifier);
- emitNet(NotesEvents.UPDATE_NOTE_SUCCESS, src);
-
- emitNet(NotesEvents.ACTION_RESULT, src, {
- message: 'NOTES_UPDATE_SUCCESS',
- type: 'success',
- });
+ await this.notesDB.updateNote(reqObj.data, identifier);
+ resp({ status: 'ok' });
} catch (e) {
- emitNet(NotesEvents.UPDATE_NOTE_FAILURE, src);
- emitNet(NotesEvents.ACTION_RESULT, src, {
- message: 'NOTES_UPDATE_FAILED',
- type: 'error',
- });
notesLogger.error(`Error in handleUpdateNote, ${e.message}`);
+ resp({ status: 'error', errorMsg: 'DB_ERROR' });
}
}
@@ -69,23 +60,17 @@ class _NotesService {
// // To implement someday
// }
- async handleDeleteNote(src: number, noteId: number) {
- const identifier = PlayerService.getIdentifier(src);
+ async handleDeleteNote(
+ reqObj: PromiseRequest,
+ resp: PromiseEventResp,
+ ) {
+ const identifier = PlayerService.getIdentifier(reqObj.source);
try {
- await this.notesDB.deleteNote(noteId, identifier);
-
- emitNet(NotesEvents.DELETE_NOTE_SUCCESS, src);
-
- emitNet(NotesEvents.ACTION_RESULT, src, {
- message: 'NOTES_DELETE_SUCCESS',
- type: 'success',
- });
+ await this.notesDB.deleteNote(reqObj.data.id, identifier);
+ resp({ status: 'ok', data: reqObj.data });
} catch (e) {
notesLogger.error(`Error in handleDeleteNote, ${e.message}`);
- emitNet(NotesEvents.ACTION_RESULT, src, {
- message: 'NOTES_DELETE_FAILED',
- type: 'error',
- });
+ resp({ status: 'error', errorMsg: 'DB_ERROR' });
}
}
}
diff --git a/typings/notes.ts b/typings/notes.ts
index c33cae8..be96a7d 100644
--- a/typings/notes.ts
+++ b/typings/notes.ts
@@ -13,25 +13,26 @@ export interface INotesAlert {
setAlert: (type: AlertCategory) => void;
}
-export interface Note {
- id?: number;
+export interface BeforeDBNote {
title: string;
content: string;
}
+export interface NoteItem extends BeforeDBNote {
+ id: number;
+ title: string;
+ content: string;
+}
+
+export interface DeleteNoteDTO {
+ id: number;
+}
+
export enum NotesEvents {
ADD_NOTE = 'npwd:addNote',
FETCH_ALL_NOTES = 'npwd:fetchAllNotes',
- SEND_NOTE = 'npwd:sendNote',
- SEND_NOTE_SUCCESS = 'npwd:sendNoteSuccess',
DELETE_NOTE = 'npwd:deleteNote',
- DELETE_NOTE_SUCCESS = 'npwd:deleteNoteSuccess',
UPDATE_NOTE = 'npwd:updateNote',
- UPDATE_NOTE_SUCCESS = 'npwd:updateNoteSuccess',
- UPDATE_NOTE_FAILURE = 'npwd:updateNoteFailure',
- ACTION_RESULT = 'npwd:notesActionResult',
- SEND_ALERT = 'npwd:notesSetAlert',
- SERVER_RESP = 'npwd:notesServerResp',
}
export interface NoteServerResponse {