mirror of
https://github.com/darksaid98/new-phone-who-dis.git
synced 2026-12-04 06:28:51 +00:00
refactor(notes): Refactor to new promise event format
This commit is contained in:
1 parent
bb81ab6fe2
commit
44a9595463
16 files changed
+394
-332
No files matched your search
@@ -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();
|
||||
|
||||
@@ -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 = () => {
|
||||
<AppTitle app={notesApp} />
|
||||
<NoteModal />
|
||||
<AppContent>
|
||||
<Route path="/notes" component={NoteList} />
|
||||
<React.Suspense fallback={<LoadingSpinner />}>
|
||||
<Route path="/notes" component={NoteList} />
|
||||
</React.Suspense>
|
||||
</AppContent>
|
||||
<Fab className={classes.absolute} onClick={onClickCreate} color="primary">
|
||||
<AddIcon />
|
||||
@@ -38,22 +39,3 @@ export const NotesApp = () => {
|
||||
</NotesThemeProvider>
|
||||
);
|
||||
};
|
||||
|
||||
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',
|
||||
},
|
||||
],
|
||||
},
|
||||
]);
|
||||
@@ -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<NoteItem[]>({
|
||||
key: 'defaultNoteItems',
|
||||
get: async () => {
|
||||
try {
|
||||
const resp = await fetchNui<ServerPromiseResp<NoteItem[]>>(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<Partial<NoteItem> | 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);
|
||||
@@ -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 };
|
||||
};
|
||||
@@ -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 };
|
||||
};
|
||||
@@ -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 };
|
||||
};
|
||||
@@ -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);
|
||||
};
|
||||
@@ -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 (
|
||||
<List disablePadding>
|
||||
{notes.map((note) => (
|
||||
<ListItem key={note.id} button divider onClick={() => handleNoteModal(note)}>
|
||||
<ListItemText>{note.title}</ListItemText>
|
||||
</ListItem>
|
||||
))}
|
||||
</List>
|
||||
);
|
||||
|
||||
return (
|
||||
<List disablePadding>
|
||||
{notes.map((note) => (
|
||||
<ListItem key={note.id} button divider onClick={() => handleNoteModal(note)}>
|
||||
<ListItemText>{note.title}</ListItemText>
|
||||
</ListItem>
|
||||
))}
|
||||
</List>
|
||||
<Box
|
||||
display="flex"
|
||||
justifyContent="center"
|
||||
alignItems="center"
|
||||
flexDirection="column"
|
||||
height="100%"
|
||||
className={classes.noNotes}
|
||||
>
|
||||
<Typography color="inherit" variant="h6" style={{ fontWeight: 300 }}>
|
||||
You have no notes
|
||||
</Typography>
|
||||
</Box>
|
||||
);
|
||||
};
|
||||
|
||||
|
||||
@@ -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<ServerPromiseResp<NoteItem>>(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<ServerPromiseResp<DeleteNoteDTO>>(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<ServerPromiseResp>(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<HTMLInputElement>) => {
|
||||
setNoteTitle(e.target.value);
|
||||
};
|
||||
|
||||
const handleContentChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
setNoteContent(e.target.value);
|
||||
};
|
||||
|
||||
const _handleClose = () => {
|
||||
setSelectedNote(null);
|
||||
};
|
||||
|
||||
if (selectedNote === null) return null;
|
||||
|
||||
return (
|
||||
<Slide direction="left" in={!!detail} mountOnEnter unmountOnExit>
|
||||
<Slide direction="left" in={Boolean(selectedNote)} mountOnEnter unmountOnExit>
|
||||
<Paper className={classes.modalRoot} square>
|
||||
{!detail ? (
|
||||
<CircularProgress />
|
||||
) : (
|
||||
<Container>
|
||||
<Box>
|
||||
<Box py={2}>
|
||||
<Button
|
||||
color="primary"
|
||||
size="large"
|
||||
startIcon={<ArrowBackIcon fontSize="large" />}
|
||||
onClick={_handleClose}
|
||||
>
|
||||
{t('APPS_NOTES')}
|
||||
</Button>
|
||||
</Box>
|
||||
<TextField
|
||||
className={classes.input}
|
||||
rowsMax={1}
|
||||
label={t('GENERIC_TITLE')}
|
||||
inputProps={{
|
||||
className: classes.inputPropsTitle,
|
||||
maxLength: 25,
|
||||
}}
|
||||
fullWidth
|
||||
value={detail.title}
|
||||
onChange={(e) => setDetail((d) => ({ ...d, title: e.target.value }))}
|
||||
/>
|
||||
<TextField
|
||||
className={classes.input}
|
||||
inputProps={{
|
||||
className: classes.inputPropsContent,
|
||||
maxLength: 250,
|
||||
}}
|
||||
label={t('GENERIC_CONTENT')}
|
||||
multiline
|
||||
fullWidth
|
||||
rows={16}
|
||||
variant="outlined"
|
||||
value={detail.content}
|
||||
onChange={(e) => setDetail((d) => ({ ...d, content: e.target.value }))}
|
||||
/>
|
||||
<Typography paragraph>{detail.content.length}/250</Typography>
|
||||
{!detail.id ? (
|
||||
<>
|
||||
<Box display="inline" p={1}>
|
||||
<Button
|
||||
color="primary"
|
||||
variant="contained"
|
||||
disabled={detail.title.length > 0 ? false : true}
|
||||
onClick={handleNoteSave}
|
||||
>
|
||||
{t('GENERIC_SAVE')}
|
||||
</Button>
|
||||
</Box>
|
||||
<Box display="inline" p={1}>
|
||||
<StatusButton color="error" variant="contained" onClick={_handleClose}>
|
||||
{t('GENERIC_CANCEL')}
|
||||
</StatusButton>
|
||||
</Box>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Box display="inline" p={1}>
|
||||
<Button color="primary" variant="contained" onClick={handleUpdateNote}>
|
||||
{t('GENERIC_UPDATE')}
|
||||
</Button>
|
||||
</Box>
|
||||
<Box display="inline" p={1}>
|
||||
<StatusButton color="error" variant="contained" onClick={handleDeleteNote}>
|
||||
{t('GENERIC_DELETE')}
|
||||
</StatusButton>
|
||||
</Box>
|
||||
</>
|
||||
)}
|
||||
<Container>
|
||||
<Box>
|
||||
<Box py={2}>
|
||||
<Button
|
||||
color="primary"
|
||||
size="large"
|
||||
startIcon={<ArrowBackIcon fontSize="large" />}
|
||||
onClick={_handleClose}
|
||||
>
|
||||
{t('APPS_NOTES')}
|
||||
</Button>
|
||||
</Box>
|
||||
</Container>
|
||||
)}
|
||||
<TextField
|
||||
className={classes.input}
|
||||
rowsMax={1}
|
||||
label={t('GENERIC_TITLE')}
|
||||
inputProps={{
|
||||
className: classes.inputPropsTitle,
|
||||
maxLength: 25,
|
||||
}}
|
||||
fullWidth
|
||||
value={noteTitle}
|
||||
onChange={handleTitleChange}
|
||||
/>
|
||||
<TextField
|
||||
className={classes.input}
|
||||
inputProps={{
|
||||
className: classes.inputPropsContent,
|
||||
maxLength: 250,
|
||||
}}
|
||||
label={t('GENERIC_CONTENT')}
|
||||
multiline
|
||||
fullWidth
|
||||
rows={16}
|
||||
variant="outlined"
|
||||
value={noteContent}
|
||||
onChange={handleContentChange}
|
||||
/>
|
||||
<Typography paragraph>{noteContent.length}/250</Typography>
|
||||
{isNewNote ? (
|
||||
<>
|
||||
<Box display="inline" p={1}>
|
||||
<Button
|
||||
color="primary"
|
||||
variant="contained"
|
||||
disabled={noteTitle.length <= 0}
|
||||
onClick={handleNoteSave}
|
||||
>
|
||||
{t('GENERIC_SAVE')}
|
||||
</Button>
|
||||
</Box>
|
||||
<Box display="inline" p={1}>
|
||||
<StatusButton color="error" variant="contained" onClick={_handleClose}>
|
||||
{t('GENERIC_CANCEL')}
|
||||
</StatusButton>
|
||||
</Box>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Box display="inline" p={1}>
|
||||
<Button
|
||||
color="primary"
|
||||
variant="contained"
|
||||
onClick={handleUpdateNote}
|
||||
disabled={noteTitle.length <= 0}
|
||||
>
|
||||
{t('GENERIC_UPDATE')}
|
||||
</Button>
|
||||
</Box>
|
||||
<Box display="inline" p={1}>
|
||||
<StatusButton color="error" variant="contained" onClick={handleDeleteNote}>
|
||||
{t('GENERIC_DELETE')}
|
||||
</StatusButton>
|
||||
</Box>
|
||||
</>
|
||||
)}
|
||||
</Box>
|
||||
</Container>
|
||||
</Paper>
|
||||
</Slide>
|
||||
);
|
||||
|
||||
@@ -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',
|
||||
},
|
||||
];
|
||||
@@ -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) => {
|
||||
|
||||
@@ -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);
|
||||
@@ -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<BeforeDBNote, NoteItem>(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<void, NoteItem[]>(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<DeleteNoteDTO, DeleteNoteDTO>(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<NoteItem, void>(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' });
|
||||
});
|
||||
});
|
||||
@@ -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<void> {
|
||||
async addNote(identifier: string, note: BeforeDBNote): Promise<number> {
|
||||
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 (<ResultSetHeader>result).insertId;
|
||||
}
|
||||
|
||||
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 fetchNotes(identifier: string): Promise<NoteItem[]> {
|
||||
const query = 'SELECT * FROM npwd_notes WHERE identifier = ? ORDER BY id DESC';
|
||||
const [result] = await pool.query(query, [identifier]);
|
||||
return <NoteItem[]>result;
|
||||
}
|
||||
|
||||
async deleteNote(noteId: number, identifier: string): Promise<void> {
|
||||
@@ -22,7 +21,7 @@ export class _NotesDB {
|
||||
await pool.query(query, [noteId, identifier]);
|
||||
}
|
||||
|
||||
async updateNote(note: Note, identifier: string): Promise<void> {
|
||||
async updateNote(note: NoteItem, 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]);
|
||||
}
|
||||
|
||||
@@ -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<void> {
|
||||
async handleAddNote(
|
||||
reqObj: PromiseRequest<BeforeDBNote>,
|
||||
resp: PromiseEventResp<NoteItem>,
|
||||
): Promise<void> {
|
||||
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<void>, resp: PromiseEventResp<NoteItem[]>) {
|
||||
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<NoteItem>, resp: PromiseEventResp<void>) {
|
||||
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<DeleteNoteDTO>,
|
||||
resp: PromiseEventResp<DeleteNoteDTO>,
|
||||
) {
|
||||
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' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+11
-10
@@ -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<T = unknown> {
|
||||
|
||||
Reference in new issue
Block a user