Feat/refactor matchmaker promise format (#293)

This commit is contained in:
chip authored and GitHub committed 2021-08-01 00:26:10 +02:00
1 parent 7ed5f54709
commit 1253c76aef
28 files changed
+2144 -3159

No files matched your search

-25
View File
@@ -1,4 +1,3 @@
require('dotenv').config();
const path = require('path'); const path = require('path');
const { const {
@@ -9,8 +8,6 @@ const {
throwUnexpectedConfigError, throwUnexpectedConfigError,
} = require('@craco/craco'); } = require('@craco/craco');
const SentryCliPlugin = require('@sentry/webpack-plugin');
const throwError = (message) => const throwError = (message) =>
throwUnexpectedConfigError({ throwUnexpectedConfigError({
packageName: 'craco', packageName: 'craco',
@@ -22,28 +19,6 @@ const throwError = (message) =>
module.exports = { module.exports = {
webpack: { webpack: {
configure: (webpackConfig, { paths }) => { configure: (webpackConfig, { paths }) => {
const releaseVersion = process.env.npm_package_version;
process.env.REACT_APP_SENTRY_RELEASE = releaseVersion;
if (process.env.SENTRY_RELEASE) {
webpackConfig.plugins.push(
new SentryCliPlugin({
url: 'https://sentry.projecterror.dev',
authToken: process.env.SENTRY_AUTH_TOKEN,
org: 'project-error',
project: 'npwd',
release: releaseVersion,
validate: true,
urlPrefix: '~/resources/html',
// webpack-specific configuration
include: ['../resources/html'],
ignore: ['node_modules'],
}),
);
}
const { hasFoundAny, matches } = getLoaders(webpackConfig, loaderByName('babel-loader')); const { hasFoundAny, matches } = getLoaders(webpackConfig, loaderByName('babel-loader'));
if (!hasFoundAny) throwError('failed to find babel-loader'); if (!hasFoundAny) throwError('failed to find babel-loader');
+3 -2
View File
@@ -10,7 +10,6 @@ import { useSimcardService } from './os/simcard/hooks/useSimcardService';
import { usePhoneService } from './os/phone/hooks/usePhoneService'; import { usePhoneService } from './os/phone/hooks/usePhoneService';
import { useApps } from './os/apps/hooks/useApps'; import { useApps } from './os/apps/hooks/useApps';
import { useTwitterService } from './apps/twitter/hooks/useTwitterService'; import { useTwitterService } from './apps/twitter/hooks/useTwitterService';
import { useMatchService } from './apps/match/hooks/useMatchService';
import { useMarketplaceService } from './apps/marketplace/hooks/useMarketplaceService'; import { useMarketplaceService } from './apps/marketplace/hooks/useMarketplaceService';
import { useBankService } from './apps/bank/hooks/useBankService'; import { useBankService } from './apps/bank/hooks/useBankService';
import { useMessagesService } from './apps/messages/hooks/useMessageService'; import { useMessagesService } from './apps/messages/hooks/useMessageService';
@@ -31,6 +30,7 @@ import PhoneWrapper from './PhoneWrapper';
import dayjs from 'dayjs'; import dayjs from 'dayjs';
import DefaultConfig from '../../config.json'; import DefaultConfig from '../../config.json';
import { TopLevelErrorComponent } from './ui/components/TopLevelErrorComponent'; import { TopLevelErrorComponent } from './ui/components/TopLevelErrorComponent';
import { useConfig } from './os/phone/hooks/useConfig';
function Phone() { function Phone() {
const { t, i18n } = useTranslation(); const { t, i18n } = useTranslation();
@@ -59,11 +59,12 @@ function Phone() {
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
}, []); }, []);
useConfig();
useKeyboardService(); useKeyboardService();
usePhoneService(); usePhoneService();
useSimcardService(); useSimcardService();
useTwitterService(); useTwitterService();
useMatchService();
useMarketplaceService(); useMarketplaceService();
useBankService(); useBankService();
useMessagesService(); useMessagesService();
@@ -49,16 +49,6 @@ export const TransactionList = () => {
</div> </div>
</div> </div>
))} ))}
<TablePagination
rowsPerPageOptions={[3, 5]}
className={classes.pagination}
component="div"
count={transactionList.length}
rowsPerPage={rowsPerPage}
page={page}
onChangePage={handleChangePage}
onChangeRowsPerPage={handleChangeRowsPerPage}
/>
</div> </div>
</div> </div>
); );
+6 -135
View File
@@ -1,29 +1,16 @@
import React, { useState, useEffect } from 'react'; import React, { useState } from 'react';
import { Route } from 'react-router-dom';
import { AppWrapper } from '../../../ui/components'; import { AppWrapper } from '../../../ui/components';
import { AppTitle } from '../../../ui/components/AppTitle'; import { AppTitle } from '../../../ui/components/AppTitle';
import { AppContent } from '../../../ui/components/AppContent'; import { AppContent } from '../../../ui/components/AppContent';
import { useApp } from '../../../os/apps/hooks/useApps'; import { useApp } from '../../../os/apps/hooks/useApps';
import InjectDebugData from '../../../os/debug/InjectDebugData';
import { MatchThemeProvider } from '../providers/MatchThemeProvider'; import { MatchThemeProvider } from '../providers/MatchThemeProvider';
import { useNuiRequest } from 'fivem-nui-react-lib';
import MatchBottomNavigation from '../components/BottomNavigation'; import MatchBottomNavigation from '../components/BottomNavigation';
import MatchPage from './views/MatchPage'; import MatchContainer from './MatchContainer';
import ProfileEditor from './views/ProfileEditor';
import MatchList from './views/MatchList';
import { MatchEvents } from '../../../../../typings/match';
import { useProfile } from '../hooks/useProfile';
export const MatchApp = () => { export const MatchApp = () => {
const Nui = useNuiRequest();
const match = useApp('MATCH'); const match = useApp('MATCH');
const [activePage, setActivePage] = useState(0); const [activePage, setActivePage] = useState(0);
const { noProfileExists } = useProfile();
useEffect(() => {
Nui.send(MatchEvents.INITIALIZE);
}, [Nui]);
const handlePageChange = (e, page) => setActivePage(page); const handlePageChange = (e, page) => setActivePage(page);
@@ -31,127 +18,11 @@ export const MatchApp = () => {
<MatchThemeProvider> <MatchThemeProvider>
<AppWrapper id="contact-app"> <AppWrapper id="contact-app">
<AppTitle app={match} /> <AppTitle app={match} />
{noProfileExists ? ( <AppContent>
<AppContent> <MatchContainer />
<ProfileEditor /> </AppContent>
</AppContent> <MatchBottomNavigation activePage={activePage} handleChange={handlePageChange} />
) : (
<>
<AppContent>
<Route path="/match/" exact component={MatchPage} />
<Route path="/match/matches" exact component={MatchList} />
<Route path="/match/profile" exact component={ProfileEditor} />
</AppContent>
<MatchBottomNavigation activePage={activePage} handleChange={handlePageChange} />
</>
)}
</AppWrapper> </AppWrapper>
</MatchThemeProvider> </MatchThemeProvider>
); );
}; };
InjectDebugData(
[
{
app: 'MATCH',
method: MatchEvents.GET_PROFILES_SUCCESS,
data: [
{
id: 1,
image:
'https://cdn.vox-cdn.com/thumbor/9xCALlkm2Mc0HQk8kMr1Ui3YNbc=/0x0:5464x3070/920x613/filters:focal(2295x1098:3169x1972):format(webp)/cdn.vox-cdn.com/uploads/chorus_image/image/67031748/shutterstock_1450403549.0.jpg',
name: 'Evan You',
bio: 'Husband, father of two, independent open source developer. Creator / project lead of @vuejs, @vite_js and connoisseur of sushi.',
createdAt: 1615932985,
updatedAt: 1615932985,
lastActive: 1616004986,
job: 'Gardener',
location: 'Grapeseed',
tags: 'shit framework, vue sucks',
phoneNumber: '987-6543',
},
{
id: 2,
image:
'https://media.cntraveler.com/photos/5f8f09c3a078e9112956774d/16:9/w_1600%2Cc_limit/Chicago-GettyImages-1065188752.jpg',
name: 'Person Beta',
bio: 'l impedit quo minus id quod maxime placeat facere possimus',
createdAt: 1615846585,
updatedAt: 1615846585,
lastActive: 1615850185,
job: 'Mechanic',
location: 'Harmony',
tags: 'tinkering,robotics',
phoneNumber: '654-3219',
},
{
id: 3,
image: 'https://www.langan.com/wp-content/uploads/2019/02/Boston-996x554.jpg',
name: 'Person Charlie',
bio: 'ut aut reiciendis voluptatibus',
createdAt: 1615850185,
updatedAt: 1615850185,
lastActive: 1613607385,
job: 'Lawyer',
location: 'Los Santos',
tags: 'reading,coolstuff, coffee',
phoneNumber: '123-4567',
},
],
},
{
app: 'MATCH',
method: MatchEvents.GET_MY_PROFILE_SUCCESS,
data: {
id: 4,
image:
'https://www.middlebury.edu/institute/sites/www.middlebury.edu.institute/files/styles/1040x585/public/2018-10/Nashville-skyline.jpg?fv=mS11EKrT&itok=HNhHqYUX',
name: 'Kire Says',
bio: "Kire's cool profile that has many cool things. And others.",
createdAt: 1615932985,
updatedAt: 1615932985,
lastActive: 1616004986,
job: 'Engineer',
location: 'Boston',
tags: 'code,books',
phoneNumber: '999-9999',
},
},
{
app: 'MATCH',
method: MatchEvents.GET_MATCHES_SUCCESS,
data: [
{
id: 5,
image:
'https://media.cntraveler.com/photos/5f8f09c3a078e9112956774d/16:9/w_1600%2Cc_limit/Chicago-GettyImages-1065188752.jpg',
name: 'Person Delta',
bio: 'l impedit quo minus id quod maxime placeat facere possimus',
createdAt: 1615846585,
updatedAt: 1615846585,
lastActive: 1615850185,
matchedAt: 1613607385,
job: 'Mechanic',
location: 'Harmony',
tags: 'tinkering,robotics',
phoneNumber: '654-3219',
},
{
id: 6,
image: 'https://www.langan.com/wp-content/uploads/2019/02/Boston-996x554.jpg',
name: 'Person Echo',
bio: 'ut aut reiciendis voluptatibus',
createdAt: 1615850185,
updatedAt: 1615850185,
lastActive: 1613607385,
job: 'Lawyer',
location: 'Los Santos',
tags: 'reading,coolstuff, coffee',
phoneNumber: '123-4567',
matchedAt: 1613607385,
},
],
},
],
200,
);
@@ -0,0 +1,35 @@
import React, { useEffect } from 'react';
import { LoadingSpinner } from '../../../ui/components/LoadingSpinner';
import ProfileEditor from './views/ProfileEditor';
import { Route } from 'react-router-dom';
import MatchPage from './views/MatchPage';
import MatchList from './views/MatchList';
import { useProfile } from '../hooks/useProfile';
const MatchContainer: React.FC = () => {
const { profile, noProfileExists, setNoProfileExists } = useProfile();
useEffect(() => {
if (!profile) {
setNoProfileExists(true);
} else {
setNoProfileExists(false);
}
}, [setNoProfileExists, profile]);
return (
<React.Suspense fallback={<LoadingSpinner />}>
{noProfileExists ? (
<ProfileEditor />
) : (
<>
<Route path="/match/" exact component={MatchPage} />
<Route path="/match/matches" exact component={MatchList} />
<Route path="/match/profile" exact component={ProfileEditor} />
</>
)}
</React.Suspense>
);
};
export default MatchContainer;
@@ -6,7 +6,6 @@ import { useTranslation } from 'react-i18next';
import { FormattedProfile, FormattedMatch } from '../../../../../../typings/match'; import { FormattedProfile, FormattedMatch } from '../../../../../../typings/match';
const useStyles = makeStyles({ const useStyles = makeStyles({
root: {},
tags: { tags: {
position: 'absolute', position: 'absolute',
bottom: '40%', bottom: '40%',
@@ -1,7 +1,6 @@
import React, { useState } from 'react'; import React, { useState } from 'react';
import { makeStyles } from '@material-ui/core/styles'; import { makeStyles } from '@material-ui/core/styles';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { useNuiRequest } from 'fivem-nui-react-lib';
import { import {
Profile as IProfile, Profile as IProfile,
FormattedProfile, FormattedProfile,
@@ -13,6 +12,10 @@ import { Card } from '@material-ui/core';
import Profile from './Profile'; import Profile from './Profile';
import { usePhone } from '../../../../os/phone/hooks/usePhone'; import { usePhone } from '../../../../os/phone/hooks/usePhone';
import PageText from '../PageText'; import PageText from '../PageText';
import { fetchNui } from '../../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../../typings/common';
import { useSnackbar } from '../../../../ui/hooks/useSnackbar';
import { useSetMyProfile } from '../../hooks/state';
const useStyles = makeStyles({ const useStyles = makeStyles({
root: { root: {
@@ -39,10 +42,11 @@ interface IProps {
} }
export function ProfileForm({ profile, showPreview }: IProps) { export function ProfileForm({ profile, showPreview }: IProps) {
const Nui = useNuiRequest();
const classes = useStyles(); const classes = useStyles();
const { t } = useTranslation(); const { t } = useTranslation();
const { ResourceConfig } = usePhone(); const { ResourceConfig } = usePhone();
const { addAlert } = useSnackbar();
const setMyProfile = useSetMyProfile();
// note that this assumes we are defensively checking // note that this assumes we are defensively checking
// that profile is not null in a parent above this component. // that profile is not null in a parent above this component.
@@ -74,10 +78,24 @@ export function ProfileForm({ profile, showPreview }: IProps) {
tags: update.tagList.join(','), tags: update.tagList.join(','),
}; };
const event = profile ? MatchEvents.UPDATE_MY_PROFILE : MatchEvents.CREATE_MY_PROFILE; const event = profile ? MatchEvents.UPDATE_MY_PROFILE : MatchEvents.CREATE_MY_PROFILE;
Nui.send(event, updatedProfile); fetchNui<ServerPromiseResp<FormattedProfile>>(event, updatedProfile).then((resp) => {
if (resp.status !== 'ok') {
return addAlert({
message: 'APPS_MATCH_UPDATE_PROFILE_FAILED',
type: 'error',
});
}
setMyProfile(resp.data);
addAlert({
message: 'APPS_MATCH_UPDATE_PROFILE_SUCCEEDED',
type: 'success',
});
});
}; };
if (!profile && !ResourceConfig.match.allowEditableProfileName) { if (!profile /* && !ResourceConfig.match.allowEditableProfileName*/) {
return <PageText text={t('APPS_MATCH_PROFILE_CONFIGURATION')} />; return <PageText text={t('APPS_MATCH_PROFILE_CONFIGURATION')} />;
} }
@@ -108,6 +126,7 @@ export function ProfileForm({ profile, showPreview }: IProps) {
value={update.bio} value={update.bio}
handleChange={setBio} handleChange={setBio}
multiline multiline
maxLength={250}
/> />
<ProfileField <ProfileField
label={t('APPS_MATCH_EDIT_PROFILE_LOCATION')} label={t('APPS_MATCH_EDIT_PROFILE_LOCATION')}
@@ -118,6 +137,7 @@ export function ProfileForm({ profile, showPreview }: IProps) {
label={t('APPS_MATCH_EDIT_PROFILE_JOB')} label={t('APPS_MATCH_EDIT_PROFILE_JOB')}
value={update.job} value={update.job}
handleChange={setJob} handleChange={setJob}
maxLength={50}
/> />
<ProfileField label={t('APPS_MATCH_EDIT_PROFILE_TAGS')} value={tags} handleChange={setTags} /> <ProfileField label={t('APPS_MATCH_EDIT_PROFILE_TAGS')} value={tags} handleChange={setTags} />
<UpdateButton handleClick={handleUpdate} loading={false} /> <UpdateButton handleClick={handleUpdate} loading={false} />
@@ -1,13 +1,11 @@
import React, { useEffect, useState } from 'react'; import React from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { Box, makeStyles } from '@material-ui/core'; import { Box, makeStyles } from '@material-ui/core';
import { useMatches } from '../../hooks/useMatches';
import Loader from '../Loader'; import Loader from '../Loader';
import PageText from '../PageText'; import PageText from '../PageText';
import Match from '../matches/Match'; import Match from '../matches/Match';
import { useNuiRequest } from 'fivem-nui-react-lib'; import { useMatches } from '../../hooks/useMatches';
import { MatchEvents } from '../../../../../../typings/match';
const useStyles = makeStyles({ const useStyles = makeStyles({
root: { root: {
@@ -15,30 +13,13 @@ const useStyles = makeStyles({
}, },
}); });
const MINIMUM_LOAD_TIME = 1500;
function MatchList() { function MatchList() {
const Nui = useNuiRequest();
const classes = useStyles(); const classes = useStyles();
const { t } = useTranslation(); const { t } = useTranslation();
const { matches, error } = useMatches(); const { matches, error } = useMatches();
const [loaded, setLoaded] = useState(false);
// We make the conscious descion here to fetch matches everytime
// a user loads this page because this list is dependent on
// other player's database interactions (i.e. their likes/dislikes)
// not just the current players.
// This is less performant but means that we will always have the
// correct state when the player views this page
useEffect(() => {
Nui.send(MatchEvents.GET_MATCHES);
window.setTimeout(() => {
setLoaded(true);
}, MINIMUM_LOAD_TIME);
}, [Nui]);
if (error) return <PageText text={t('APPS_MATCH_MATCHES_ERROR')} />; if (error) return <PageText text={t('APPS_MATCH_MATCHES_ERROR')} />;
if (!loaded || !matches) return <Loader />; if (!matches) return <Loader />;
if (matches.length === 0) return <PageText text={t('APPS_MATCH_NO_MATCHES')} />; if (matches.length === 0) return <PageText text={t('APPS_MATCH_NO_MATCHES')} />;
return ( return (
@@ -7,6 +7,7 @@ import { useProfiles } from '../../hooks/useProfiles';
import Loader from '../Loader'; import Loader from '../Loader';
import PageText from '../PageText'; import PageText from '../PageText';
import ActiveProfile from '../ActiveProfile'; import ActiveProfile from '../ActiveProfile';
import { useMatchActions } from '../../hooks/useMatchActions';
const useStyles = makeStyles({ const useStyles = makeStyles({
root: { root: {
@@ -23,7 +24,8 @@ const MINIMUM_LOAD_TIME = 1250;
const MatchPage = () => { const MatchPage = () => {
const classes = useStyles(); const classes = useStyles();
const { t } = useTranslation(); const { t } = useTranslation();
const { profiles, error, activeProfile, setViewed } = useProfiles(); const { profiles, error, activeProfile } = useProfiles();
const { setViewed } = useMatchActions();
const [loaded, setLoaded] = useState(false); const [loaded, setLoaded] = useState(false);
useEffect(() => { useEffect(() => {
@@ -2,10 +2,9 @@ import React, { useState } from 'react';
import { useTranslation } from 'react-i18next'; import { useTranslation } from 'react-i18next';
import { makeStyles } from '@material-ui/core/styles'; import { makeStyles } from '@material-ui/core/styles';
import { Box, FormControlLabel, Switch } from '@material-ui/core'; import { Box, FormControlLabel, Switch } from '@material-ui/core';
import { useProfile } from '../../hooks/useProfile';
import Loader from '../Loader'; import Loader from '../Loader';
import ProfileForm from '../profile/ProfileForm'; import ProfileForm from '../profile/ProfileForm';
import { useProfile } from '../../hooks/useProfile';
const useStyles = makeStyles({ const useStyles = makeStyles({
root: { root: {
+75 -6
View File
@@ -1,18 +1,55 @@
import { atom } from 'recoil'; import { atom, selector, useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
import { FormattedMatch, FormattedProfile } from '../../../../../typings/match'; import { FormattedMatch, FormattedProfile, MatchEvents } from '../../../../../typings/match';
import { fetchNui } from '../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../typings/common';
import LogDebugEvent from '../../../os/debug/LogDebugEvents';
import { isEnvBrowser } from '../../../utils/misc';
import { MockMatchesData, MockMyProfileData, MockProfilesData } from '../utils/constants';
export const matchState = { export const matchState = {
profiles: atom<FormattedProfile[]>({ profiles: atom<FormattedProfile[]>({
key: 'profiles', key: 'profiles',
default: null, default: selector({
key: 'matchDefaultProfiles',
get: async () => {
try {
const resp = await fetchNui<ServerPromiseResp<FormattedProfile[]>>(
MatchEvents.GET_PROFILES,
);
LogDebugEvent({ action: 'fetchProfiles', data: resp.data });
return resp.data;
} catch (e) {
if (isEnvBrowser()) {
return MockProfilesData;
}
console.error(e);
return [];
}
},
}),
}), }),
errorLoadingProfiles: atom({ errorLoadingProfiles: atom<boolean>({
key: 'errorLoadingProfiles', key: 'errorLoadingProfiles',
default: false, default: false,
}), }),
matches: atom<FormattedMatch[]>({ matches: atom<FormattedMatch[]>({
key: 'matches', key: 'matches',
default: null, default: selector({
key: 'defaultMatches',
get: async () => {
try {
const resp = await fetchNui<ServerPromiseResp<FormattedMatch[]>>(MatchEvents.GET_MATCHES);
LogDebugEvent({ action: 'fetchMatches', data: resp.data });
return resp.data;
} catch (e) {
if (isEnvBrowser()) {
return MockMatchesData;
}
console.log(e);
return [];
}
},
}),
}), }),
errorLoadingMatches: atom<boolean>({ errorLoadingMatches: atom<boolean>({
key: 'errorLoadingMatches', key: 'errorLoadingMatches',
@@ -20,10 +57,42 @@ export const matchState = {
}), }),
myProfile: atom<FormattedProfile | null>({ myProfile: atom<FormattedProfile | null>({
key: 'myProfile', key: 'myProfile',
default: null, default: selector({
key: 'myProfileDefault',
get: async () => {
try {
const resp = await fetchNui<ServerPromiseResp<FormattedProfile>>(
MatchEvents.GET_MY_PROFILE,
);
LogDebugEvent({ action: 'fetchMyProfile', data: resp.data });
return resp.data;
} catch (e) {
if (isEnvBrowser()) {
return MockMyProfileData;
}
console.error(e);
return null;
}
},
}),
}), }),
noProfileExists: atom<boolean>({ noProfileExists: atom<boolean>({
key: 'noProfileExists', key: 'noProfileExists',
default: false, default: false,
}), }),
}; };
export const useFormattedProfiles = () => useRecoilState(matchState.profiles);
export const useFormattedProfilesValue = () => useRecoilValue(matchState.profiles);
export const useSetFormattedProfiles = () => useSetRecoilState(matchState.profiles);
export const useMyProfile = () => useRecoilState(matchState.myProfile);
export const useMyProfileValue = () => useRecoilValue(matchState.myProfile);
export const useSetMyProfile = () => useSetRecoilState(matchState.myProfile);
export const useProfileExistsValue = () => useRecoilValue(matchState.noProfileExists);
export const useProfileExists = () => useRecoilState(matchState.noProfileExists);
export const useFormattedMatches = () => useRecoilState(matchState.matches);
export const useMatchesValue = () => useRecoilValue(matchState.matches);
export const useSetMatches = () => useSetRecoilState(matchState.matches);
@@ -0,0 +1,51 @@
import { FormattedMatch, MatchEvents } from '../../../../../typings/match';
import { fetchNui } from '../../../utils/fetchNui';
import { ServerPromiseResp } from '../../../../../typings/common';
import { useSetFormattedProfiles, useSetMatches } from './state';
import { useSnackbar } from '../../../ui/hooks/useSnackbar';
import { useCallback } from 'react';
export const useMatchActions = () => {
const setProfiles = useSetFormattedProfiles();
const setMatches = useSetMatches();
const { addAlert } = useSnackbar();
const setViewed = useCallback(
(id: number, liked: boolean) => {
setProfiles((profiles) =>
profiles.map((profile) => {
if (id === profile.id) return { ...profile, viewed: true, liked };
return profile;
}),
);
fetchNui<ServerPromiseResp<boolean>>(MatchEvents.SAVE_LIKES, [{ id, liked }]).then((resp) => {
if (resp.status !== 'ok') {
return addAlert({
message: 'APPS_MATCH_SAVE_LIKES_FAILED',
type: 'error',
});
}
// Instead of just fetching the matches again, we might want to first format the profile to a 'Match',then to a 'FormattedMatch'
// and then just mutate the already existing state of matches?
// I guess that's for another time :P
if (resp.data) {
addAlert({
message: 'APPS_MATCH_NEW_LIKE_FOUND',
type: 'info',
});
fetchNui<ServerPromiseResp<FormattedMatch[]>>(MatchEvents.GET_MATCHES).then((resp) => {
setMatches(resp.data);
});
}
});
},
[setProfiles, addAlert, setMatches],
);
return {
setViewed,
};
};
@@ -1,86 +0,0 @@
import { useSetRecoilState } from 'recoil';
import { matchState } from './state';
import { useTranslation } from 'react-i18next';
import dayjs from 'dayjs';
import { useNuiEvent } from 'fivem-nui-react-lib';
import { Profile, FormattedProfile, Match, MatchEvents } from '../../../../../typings/match';
import { IAlert, useSnackbar } from '../../../ui/hooks/useSnackbar';
export const useMatchService = () => {
const { addAlert } = useSnackbar();
const { t } = useTranslation();
const setNoProfileExists = useSetRecoilState(matchState.noProfileExists);
const setProfiles = useSetRecoilState(matchState.profiles);
const setProfile = useSetRecoilState(matchState.myProfile);
const setMatches = useSetRecoilState(matchState.matches);
const setErrorLoadingMatches = useSetRecoilState(matchState.errorLoadingMatches);
const setErrorLoadingProfiles = useSetRecoilState(matchState.errorLoadingProfiles);
const handleAddAlert = ({ message, type }: IAlert) => {
addAlert({
message: t(message),
type,
});
};
function formatProfile(profile: Profile): FormattedProfile | null {
return {
...profile,
tagList: profile.tags.split(',').filter((t) => t), // remove any empty tags
lastActiveFormatted: dayjs.unix(profile.lastActive).format(t('DATE_TIME_FORMAT')),
viewed: false,
};
}
const _setProfiles = (profiles: Profile[]): void => {
setProfiles(profiles.map(formatProfile));
};
const _setProfile = (profile: Profile) => {
if (!profile) {
setNoProfileExists(true);
} else {
setNoProfileExists(false);
setProfile(formatProfile(profile));
}
};
const _handleGetProfilesFailed = (alert: IAlert): void => {
handleAddAlert(alert);
setErrorLoadingProfiles(true);
};
const _setMatches = (matches: Match[]): void => {
setMatches(
matches.map((match) => ({
...match,
tagList: match.tags.split(',').filter((t) => t), // remove any empty tags
lastActiveFormatted: dayjs.unix(match.lastActive).format(t('DATE_TIME_FORMAT')),
matchedAtFormatted: dayjs.unix(match.matchedAt).format(t('DATE_TIME_FORMAT')),
})),
);
};
const _handleGetMatchesFailed = (alert: IAlert): void => {
handleAddAlert(alert);
setErrorLoadingMatches(true);
};
const _handleUpdateProfile = (profile: Profile) => {
_setProfile(profile);
handleAddAlert({ message: 'APPS_MATCH_UPDATE_PROFILE_SUCCEEDED', type: 'info' });
};
useNuiEvent('MATCH', MatchEvents.GET_PROFILES_SUCCESS, _setProfiles);
useNuiEvent('MATCH', MatchEvents.GET_PROFILES_FAILED, _handleGetProfilesFailed);
useNuiEvent('MATCH', MatchEvents.GET_MY_PROFILE_SUCCESS, _setProfile);
useNuiEvent('MATCH', MatchEvents.GET_MY_PROFILE_FAILED, handleAddAlert);
useNuiEvent('MATCH', MatchEvents.GET_MATCHES_SUCCESS, _setMatches);
useNuiEvent('MATCH', MatchEvents.GET_MATCHES_FAILED, _handleGetMatchesFailed);
useNuiEvent('MATCH', MatchEvents.SAVE_LIKES_FAILED, handleAddAlert);
useNuiEvent('MATCH', MatchEvents.NEW_MATCH, handleAddAlert);
useNuiEvent('MATCH', MatchEvents.UPDATE_MY_PROFILE_SUCCESS, _handleUpdateProfile);
useNuiEvent('MATCH', MatchEvents.UPDATE_MY_PROFILE_FAILED, handleAddAlert);
useNuiEvent('MATCH', MatchEvents.CREATE_MY_PROFILE_SUCCESS, _handleUpdateProfile);
useNuiEvent('MATCH', MatchEvents.CREATE_MY_PROFILE_FAILED, handleAddAlert);
return {};
};
+7 -6
View File
@@ -1,15 +1,16 @@
import { matchState, useFormattedMatches } from './state';
import { useRecoilValue } from 'recoil'; import { useRecoilValue } from 'recoil';
import { matchState } from './state';
import { FormattedMatch } from '../../../../../typings/match'; import { FormattedMatch } from '../../../../../typings/match';
interface IUseMatches { interface UseMatchProps {
matches: FormattedMatch[]; matches: FormattedMatch[];
setMatches: (matches: FormattedMatch[]) => void;
error: boolean; error: boolean;
} }
export const useMatches = (): IUseMatches => { export const useMatches = (): UseMatchProps => {
const matches = useRecoilValue<FormattedMatch[]>(matchState.matches); const [matches, setMatches] = useFormattedMatches();
const error = useRecoilValue(matchState.errorLoadingMatches); const error = useRecoilValue(matchState.errorLoadingMatches);
return { matches, error };
return { matches, setMatches, error };
}; };
+8 -8
View File
@@ -1,16 +1,16 @@
import { useRecoilState, useRecoilValue } from 'recoil'; import { useMyProfile, useProfileExists } from './state';
import { matchState } from './state';
import { FormattedProfile } from '../../../../../typings/match'; import { FormattedProfile } from '../../../../../typings/match';
interface IUseProfiles { interface UseProfileProps {
profile: FormattedProfile; profile: FormattedProfile;
setProfile: (profile: FormattedProfile) => void; setProfile: (profile: FormattedProfile) => void;
noProfileExists: boolean; noProfileExists: boolean;
setNoProfileExists: (exists: boolean) => void;
} }
export const useProfile = (): IUseProfiles => { export const useProfile = (): UseProfileProps => {
const [profile, setProfile] = useRecoilState<FormattedProfile>(matchState.myProfile); const [profile, setProfile] = useMyProfile();
const noProfileExists = useRecoilValue(matchState.noProfileExists); const [noProfileExists, setNoProfileExists] = useProfileExists();
return { profile, setProfile, noProfileExists };
return { profile, setProfile, noProfileExists, setNoProfileExists };
}; };
+7 -21
View File
@@ -1,34 +1,20 @@
import { useRecoilState, useRecoilValue } from 'recoil'; import { useRecoilValue } from 'recoil';
import { matchState } from './state'; import { matchState, useFormattedProfiles } from './state';
import { FormattedProfile, MatchEvents } from '../../../../../typings/match'; import { FormattedProfile } from '../../../../../typings/match';
import { useNuiRequest } from 'fivem-nui-react-lib';
interface IUseProfiles { interface UseProfilesProps {
profiles: FormattedProfile[]; profiles: FormattedProfile[];
activeProfile: FormattedProfile | null; activeProfile: FormattedProfile | null;
setViewed: (index: number, liked: boolean) => void;
error: boolean; error: boolean;
} }
export const useProfiles = (): IUseProfiles => { export const useProfiles = (): UseProfilesProps => {
const Nui = useNuiRequest(); const [profiles] = useFormattedProfiles();
const [profiles, setProfiles] = useRecoilState(matchState.profiles);
const error = useRecoilValue(matchState.errorLoadingProfiles); const error = useRecoilValue(matchState.errorLoadingProfiles);
const setViewed = (id: number, liked: boolean) => {
setProfiles((profiles) =>
profiles.map((profile) => {
if (id === profile.id) return { ...profile, viewed: true, liked };
return profile;
}),
);
Nui.send(MatchEvents.SAVE_LIKES, [{ id, liked }]);
};
const filteredProfiles = profiles ? profiles.filter((profile) => !profile.viewed) : null; const filteredProfiles = profiles ? profiles.filter((profile) => !profile.viewed) : null;
const activeProfile = profiles ? filteredProfiles[0] : null; const activeProfile = profiles ? filteredProfiles[0] : null;
return { profiles, activeProfile, error, setViewed }; return { profiles, activeProfile, error };
}; };
+116
View File
@@ -0,0 +1,116 @@
import { FormattedMatch, FormattedProfile } from '../../../../../typings/match';
export const MockProfilesData: FormattedProfile[] = [
{
id: 1,
identifier: '3r523242',
viewed: false,
image:
'https://cdn.vox-cdn.com/thumbor/9xCALlkm2Mc0HQk8kMr1Ui3YNbc=/0x0:5464x3070/920x613/filters:focal(2295x1098:3169x1972):format(webp)/cdn.vox-cdn.com/uploads/chorus_image/image/67031748/shutterstock_1450403549.0.jpg',
name: 'Evan You',
bio: 'Husband, father of two, independent open source developer. Creator / project lead of @vuejs, @vite_js and connoisseur of sushi.',
createdAt: 1615932985,
updatedAt: 1615932985,
lastActive: 1616004986,
job: 'Gardener',
location: 'Grapeseed',
tags: 'shit framework, vue sucks',
phoneNumber: '987-6543',
tagList: ['shitframework', 'vue sucks'],
lastActiveFormatted: '1616004986',
},
{
id: 2,
identifier: '3r523242',
viewed: false,
image:
'https://media.cntraveler.com/photos/5f8f09c3a078e9112956774d/16:9/w_1600%2Cc_limit/Chicago-GettyImages-1065188752.jpg',
name: 'Person Beta',
bio: 'l impedit quo minus id quod maxime placeat facere possimus',
createdAt: 1615846585,
updatedAt: 1615846585,
lastActive: 1615850185,
job: 'Mechanic',
location: 'Harmony',
tags: 'tinkering,robotics',
phoneNumber: '654-3219',
tagList: ['tinkering', 'robotics'],
lastActiveFormatted: '12332425',
},
{
id: 3,
identifier: '3r523242',
viewed: false,
image: 'https://www.langan.com/wp-content/uploads/2019/02/Boston-996x554.jpg',
name: 'Person Charlie',
bio: 'ut aut reiciendis voluptatibus',
createdAt: 1615850185,
updatedAt: 1615850185,
lastActive: 1613607385,
job: 'Lawyer',
location: 'Los Santos',
tags: 'reading,coolstuff, coffee',
phoneNumber: '123-4567',
tagList: ['reading', 'coolstuff', 'coffee'],
lastActiveFormatted: '12332425',
},
];
export const MockMyProfileData: FormattedProfile = {
id: 4,
identifier: '4785656',
viewed: false,
image:
'https://www.middlebury.edu/institute/sites/www.middlebury.edu.institute/files/styles/1040x585/public/2018-10/Nashville-skyline.jpg?fv=mS11EKrT&itok=HNhHqYUX',
name: 'Kire Says',
bio: "Kire's cool profile that has many cool things. And others.",
createdAt: 1615932985,
updatedAt: 1615932985,
lastActive: 1616004986,
job: 'Engineer',
location: 'Boston',
tags: 'code,javascript',
phoneNumber: '999-9999',
tagList: ['code', 'javascript'],
lastActiveFormatted: '12332425',
};
export const MockMatchesData: FormattedMatch[] = [
{
id: 5,
identifier: '4785656',
viewed: true,
image:
'https://media.cntraveler.com/photos/5f8f09c3a078e9112956774d/16:9/w_1600%2Cc_limit/Chicago-GettyImages-1065188752.jpg',
name: 'Taso',
bio: 'l impedit quo minus id quod maxime placeat facere possimus',
createdAt: 1615846585,
updatedAt: 1615846585,
lastActive: 1615850185,
job: 'Mechanic',
location: 'Harmony',
tags: 'tinkering,robotics',
tagList: ['tinkering', 'robotics'],
lastActiveFormatted: '525343252',
matchedAtFormatted: '3452355',
phoneNumber: '654-3219',
},
{
id: 6,
identifier: '4785656',
viewed: true,
image: 'https://www.langan.com/wp-content/uploads/2019/02/Boston-996x554.jpg',
name: 'Chip',
bio: 'ut aut reiciendis voluptatibus',
createdAt: 1615850185,
updatedAt: 1615850185,
lastActive: 1613607385,
job: 'Lawyer',
location: 'Los Santos',
tags: 'reading,coolstuff, coffee',
tagList: ['reading', 'coolstuff', 'coffee'],
phoneNumber: '123-4567',
lastActiveFormatted: '525343252',
matchedAtFormatted: '3452355',
},
];
+1 -1
View File
@@ -5,7 +5,6 @@ import { ContactsApp } from '../../../apps/contacts/components/ContactsApp';
import { CalculatorApp } from '../../../apps/calculator/components/CalculatorApp'; import { CalculatorApp } from '../../../apps/calculator/components/CalculatorApp';
import { SettingsApp } from '../../../apps/settings/components/SettingsApp'; import { SettingsApp } from '../../../apps/settings/components/SettingsApp';
import { MessagesApp } from '../../../apps/messages/components/MessagesApp'; import { MessagesApp } from '../../../apps/messages/components/MessagesApp';
import { MatchApp } from '../../../apps/match/components/MatchApp';
import { TwitterApp } from '../../../apps/twitter/components/TwitterApp'; import { TwitterApp } from '../../../apps/twitter/components/TwitterApp';
import { ExampleApp } from '../../../apps/example/components/ExampleApp'; import { ExampleApp } from '../../../apps/example/components/ExampleApp';
import { MarketplaceApp } from '../../../apps/marketplace/components/MarketplaceApp'; import { MarketplaceApp } from '../../../apps/marketplace/components/MarketplaceApp';
@@ -35,6 +34,7 @@ import { MATCH_APP_PRIMARY_COLOR, MATCH_APP_TEXT_COLOR } from '../../../apps/mat
import { SvgIconProps } from '@material-ui/core'; import { SvgIconProps } from '@material-ui/core';
import { INotificationIcon } from '../../notifications/providers/NotificationsProvider'; import { INotificationIcon } from '../../notifications/providers/NotificationsProvider';
import { BrowserApp } from '../../../apps/browser/components/BrowserApp'; import { BrowserApp } from '../../../apps/browser/components/BrowserApp';
import { MatchApp } from '../../../apps/match/components/MatchApp';
export interface IAppConfig { export interface IAppConfig {
id: string; id: string;
+14
View File
@@ -0,0 +1,14 @@
import { useSetRecoilState } from 'recoil';
import { phoneState } from './state';
import { isEnvBrowser } from '../../../utils/misc';
export const useConfig = (): void => {
const setResourceConfig = useSetRecoilState(phoneState.resourceConfig);
if (!isEnvBrowser()) {
const resourceName = (window as any)?.GetParentResourceName() || 'npwd';
fetch(`https://cfx-nui-${resourceName}/config.json`).then(async (res) => {
const config = await res.json();
setResourceConfig(config);
});
}
};
+5 -1
View File
@@ -12,7 +12,7 @@ const useStyles = makeStyles({
}, },
}); });
function ProfileField({ label, value, handleChange, allowChange, multiline, inputRef }) { function ProfileField({ label, value, handleChange, allowChange, multiline, inputRef, maxLength }) {
const classes = useStyles(); const classes = useStyles();
const _handleChange = (e) => handleChange(e.target.value); const _handleChange = (e) => handleChange(e.target.value);
@@ -24,6 +24,9 @@ function ProfileField({ label, value, handleChange, allowChange, multiline, inpu
value={value} value={value}
onChange={_handleChange} onChange={_handleChange}
disabled={!allowChange} disabled={!allowChange}
inputProps={{
maxLength: maxLength,
}}
multiline={multiline} multiline={multiline}
inputRef={inputRef} inputRef={inputRef}
/> />
@@ -33,6 +36,7 @@ function ProfileField({ label, value, handleChange, allowChange, multiline, inpu
ProfileField.defaultProps = { ProfileField.defaultProps = {
allowChange: true, allowChange: true,
maxLength: 200,
multiline: false, multiline: false,
inputRef: null, inputRef: null,
}; };
+3 -1
View File
@@ -18,7 +18,9 @@ export async function fetchNui<T = any>(eventName: string, data?: any): Promise<
LogDebugEvent({ data, action: 'fetchNui' }); LogDebugEvent({ data, action: 'fetchNui' });
const resourceName = (window as any)?.GetParentResourceName() || 'npwd'; const resourceName = (window as any).GetParentResourceName
? (window as any).GetParentResourceName()
: 'npwd';
const resp = await fetch(`https://${resourceName}/${eventName}`, options); const resp = await fetch(`https://${resourceName}/${eventName}`, options);
+1178 -2237
View File
File diff suppressed because it is too large. Load diff
-1
View File
@@ -18,7 +18,6 @@ const exps = global.exports;
function fetchOnInitialize() { function fetchOnInitialize() {
emitNet(MessageEvents.FETCH_MESSAGE_GROUPS); emitNet(MessageEvents.FETCH_MESSAGE_GROUPS);
emitNet(TwitterEvents.GET_OR_CREATE_PROFILE); emitNet(TwitterEvents.GET_OR_CREATE_PROFILE);
sendMessage('PHONE', PhoneEvents.SET_CONFIG, config);
} }
onNet(PhoneEvents.ON_INIT, () => { onNet(PhoneEvents.ON_INIT, () => {
+8 -52
View File
@@ -1,53 +1,9 @@
import { Like, Profile, MatchEvents } from '../../typings/match'; import { MatchEvents } from '../../typings/match';
import { sendMatchEvent } from '../utils/messages'; import { RegisterNuiProxy } from './cl_utils';
/** RegisterNuiProxy(MatchEvents.GET_PROFILES);
* Many events that are just statuses are passed directly from RegisterNuiProxy(MatchEvents.GET_MY_PROFILE);
* the server to NUI and the client is just acting as a middle man. RegisterNuiProxy(MatchEvents.GET_MATCHES);
* For those cases this function allows us to simply transfer all the RegisterNuiProxy(MatchEvents.SAVE_LIKES);
* data associated with the event. RegisterNuiProxy(MatchEvents.CREATE_MY_PROFILE);
* @param eventName - event we are propagating RegisterNuiProxy(MatchEvents.UPDATE_MY_PROFILE);
*/
const transferEvent = (eventName: string) => (...args: any) => {
sendMatchEvent(eventName, ...args);
};
onNet(MatchEvents.GET_PROFILES_FAILED, transferEvent(MatchEvents.GET_PROFILES_FAILED));
onNet(MatchEvents.SAVE_LIKES_SUCCESS, transferEvent(MatchEvents.SAVE_LIKES_SUCCESS));
onNet(MatchEvents.SAVE_LIKES_FAILED, transferEvent(MatchEvents.SAVE_LIKES_FAILED));
onNet(MatchEvents.GET_MATCHES_SUCCESS, transferEvent(MatchEvents.GET_MATCHES_SUCCESS));
onNet(MatchEvents.GET_MATCHES_FAILED, transferEvent(MatchEvents.GET_MATCHES_FAILED));
onNet(MatchEvents.GET_MY_PROFILE_SUCCESS, transferEvent(MatchEvents.GET_MY_PROFILE_SUCCESS));
onNet(MatchEvents.GET_MY_PROFILE_FAILED, transferEvent(MatchEvents.GET_MY_PROFILE_FAILED));
onNet(MatchEvents.GET_PROFILES_SUCCESS, transferEvent(MatchEvents.GET_PROFILES_SUCCESS));
onNet(MatchEvents.UPDATE_MY_PROFILE_SUCCESS, transferEvent(MatchEvents.UPDATE_MY_PROFILE_SUCCESS));
onNet(MatchEvents.CREATE_MY_PROFILE_SUCCESS, transferEvent(MatchEvents.CREATE_MY_PROFILE_SUCCESS));
onNet(MatchEvents.CREATE_MY_PROFILE_FAILED, transferEvent(MatchEvents.CREATE_MY_PROFILE_FAILED));
onNet(MatchEvents.UPDATE_MY_PROFILE_FAILED, transferEvent(MatchEvents.UPDATE_MY_PROFILE_FAILED));
onNet(MatchEvents.NEW_MATCH, transferEvent(MatchEvents.NEW_MATCH));
RegisterNuiCallbackType(MatchEvents.SAVE_LIKES);
on(`__cfx_nui:${MatchEvents.SAVE_LIKES}`, (likes: Like[], cb: Function) => {
emitNet(MatchEvents.SAVE_LIKES, likes);
cb();
});
RegisterNuiCallbackType(MatchEvents.GET_MATCHES);
on(`__cfx_nui:${MatchEvents.GET_MATCHES}`, () => {
emitNet(MatchEvents.GET_MATCHES);
});
RegisterNuiCallbackType(MatchEvents.INITIALIZE);
on(`__cfx_nui:${MatchEvents.INITIALIZE}`, () => {
emitNet(MatchEvents.INITIALIZE);
});
RegisterNuiCallbackType(MatchEvents.CREATE_MY_PROFILE);
on(`__cfx_nui:${MatchEvents.CREATE_MY_PROFILE}`, (profile: Profile) => {
emitNet(MatchEvents.CREATE_MY_PROFILE, profile);
});
RegisterNuiCallbackType(MatchEvents.UPDATE_MY_PROFILE);
on(`__cfx_nui:${MatchEvents.UPDATE_MY_PROFILE}`, (profile: Profile) => {
emitNet(MatchEvents.UPDATE_MY_PROFILE, profile);
});
+60 -29
View File
@@ -1,8 +1,67 @@
import { Like, MatchEvents, Profile } from '../../../typings/match'; import {
FormattedMatch,
FormattedProfile,
Like,
MatchEvents,
Profile,
} from '../../../typings/match';
import MatchService from './match.service'; import MatchService from './match.service';
import { getSource } from '../utils/miscUtils'; import { getSource } from '../utils/miscUtils';
import { matchLogger } from './match.utils'; import { matchLogger } from './match.utils';
import { config } from '../server'; import { config } from '../server';
import { onNetPromise } from '../utils/PromiseNetEvents/onNetPromise';
onNetPromise<void, FormattedProfile[]>(MatchEvents.GET_PROFILES, (reqObj, resp) => {
MatchService.handleGetProfiles(reqObj, resp).catch((e) => {
matchLogger.error(
`Error occurred in fetch profiles event (${reqObj.source}), Error: ${e.message}`,
);
resp({ status: 'error', errorMsg: 'INTERNAL_ERROR' });
});
});
onNetPromise<void, FormattedProfile>(MatchEvents.GET_MY_PROFILE, (reqObj, resp) => {
MatchService.handleGetMyProfile(reqObj, resp).catch((e) => {
matchLogger.error(
`Error occurred in fetch my profile event (${reqObj.source}), Error: ${e.message}`,
);
resp({ status: 'error', errorMsg: 'INTERNAL_ERROR' });
});
});
onNetPromise<void, FormattedMatch[]>(MatchEvents.GET_MATCHES, (reqObj, resp) => {
MatchService.handleGetMatches(reqObj, resp).catch((e) => {
matchLogger.error(
`Error occurred in fetch matches event (${reqObj.source}), Error: ${e.message}`,
);
resp({ status: 'error', errorMsg: 'INTERNAL_ERROR' });
});
});
onNetPromise<Like[], boolean>(MatchEvents.SAVE_LIKES, (reqObj, resp) => {
MatchService.handleSaveLikes(reqObj, resp).catch((e) => {
matchLogger.error(`Error occurred in save likes event (${reqObj.source}), Error: ${e.message}`);
resp({ status: 'error', errorMsg: 'INTERNAL_ERROR' });
});
});
onNetPromise<Profile, FormattedProfile>(MatchEvents.CREATE_MY_PROFILE, (reqObj, resp) => {
MatchService.handleCreateMyProfile(reqObj, resp).catch((e) => {
matchLogger.error(
`Error occurred in create my profile event (${reqObj.source}), Error: ${e.message}`,
);
resp({ status: 'error', errorMsg: 'INTERNAL_ERROR' });
});
});
onNetPromise<Profile, FormattedProfile>(MatchEvents.UPDATE_MY_PROFILE, (reqObj, resp) => {
MatchService.handleUpdateMyProfile(reqObj, resp).catch((e) => {
matchLogger.error(
`Error occurred in update my profile event (${reqObj.source}), Error: ${e.message}`,
);
resp({ status: 'error', errorMsg: 'INTERNAL_ERROR' });
});
});
onNet(MatchEvents.INITIALIZE, () => { onNet(MatchEvents.INITIALIZE, () => {
const _source = getSource(); const _source = getSource();
@@ -11,34 +70,6 @@ onNet(MatchEvents.INITIALIZE, () => {
); );
}); });
onNet(MatchEvents.CREATE_MY_PROFILE, (profile: Profile) => {
const _source = getSource();
MatchService.handleCreateMyProfile(_source, profile).catch((e) =>
matchLogger.error(`Error occurred in createMyProfile event (${_source}), Error: ${e.message}`),
);
});
onNet(MatchEvents.UPDATE_MY_PROFILE, (profile: Profile) => {
const _source = getSource();
MatchService.handleUpdateMyProfile(_source, profile).catch((e) =>
matchLogger.error(`Error occurred in updateMyProfile event (${_source}), Error: ${e.message}`),
);
});
onNet(MatchEvents.SAVE_LIKES, (likes: Like[]) => {
const _source = getSource();
MatchService.handleSaveLikes(_source, likes).catch((e) =>
matchLogger.error(`Error occurred in saveLikes event (${_source}), Error: ${e.message}`),
);
});
onNet(MatchEvents.GET_MATCHES, () => {
const _source = getSource();
MatchService.handleGetMatches(_source).catch((e) =>
matchLogger.error(`Error occurred in getMatches event (${_source}), Error: ${e.message}`),
);
});
if (!config.match.allowEditableProfileName && !config.match.generateProfileNameFromUsers) { if (!config.match.allowEditableProfileName && !config.match.generateProfileNameFromUsers) {
const warning = const warning =
`Both allowEdtiableProfileName and generateProfileNameFromUsers ` + `Both allowEdtiableProfileName and generateProfileNameFromUsers ` +
+94 -70
View File
@@ -1,52 +1,91 @@
import { matchLogger } from './match.utils'; import { formatMatches, formatProfile, matchLogger } from './match.utils';
import MatchDB, { _MatchDB } from './match.db'; import MatchDB, { _MatchDB } from './match.db';
import { Like, MatchEvents, Profile } from '../../../typings/match'; import {
FormattedMatch,
FormattedProfile,
Like,
MatchEvents,
Profile,
} from '../../../typings/match';
import PlayerService from '../players/player.service'; import PlayerService from '../players/player.service';
import { PromiseEventResp, PromiseRequest } from '../utils/PromiseNetEvents/promise.types';
class _MatchService { class _MatchService {
private readonly matchDB: _MatchDB; private readonly matchDB: _MatchDB;
constructor() { constructor() {
this.matchDB = MatchDB; this.matchDB = MatchDB;
matchLogger.debug('Match service started'); matchLogger.debug('Match service started');
} }
async dispatchPlayerProfile(identifier: string, source: number): Promise<void> { async handleGetProfiles(
reqObj: PromiseRequest<void>,
resp: PromiseEventResp<FormattedProfile[]>,
): Promise<void> {
const identifier = PlayerService.getIdentifier(reqObj.source);
try { try {
const profile = await this.matchDB.getOrCreateProfile(identifier); const profiles = await this.dispatchProfiles(identifier);
emitNet(MatchEvents.GET_MY_PROFILE_SUCCESS, source, profile); resp({ status: 'ok', data: profiles });
} catch (e) { } catch (e) {
matchLogger.error(`Failed to get player profile, ${e.message}`); matchLogger.error(`Error in handleGetProfiles, ${e.message}`);
emitNet(MatchEvents.GET_MY_PROFILE_FAILED, source, { resp({ status: 'error', errorMsg: 'DB_ERROR' });
message: 'APPS_MATCH_GET_MY_PROFILE_FAILED',
type: 'error',
});
} }
} }
async dispatchProfiles(identifier: string, source: number): Promise<void> { async handleGetMyProfile(
reqObj: PromiseRequest<void>,
resp: PromiseEventResp<FormattedProfile>,
): Promise<void> {
const identifier = PlayerService.getIdentifier(reqObj.source);
try { try {
const profiles = await this.matchDB.getPotentialProfiles(identifier); const profile = await this.dispatchPlayerProfile(identifier);
emitNet(MatchEvents.GET_PROFILES_SUCCESS, source, profiles); resp({ status: 'ok', data: profile });
} catch (e) { } catch (e) {
matchLogger.error(`Failed to retrieve profiles, ${e.message}`); matchLogger.error(`Error in handleGetMyProfile, ${e.message}`);
emitNet(MatchEvents.GET_PROFILES_FAILED, source, { resp({ status: 'error', errorMsg: 'DB_ERROR' });
message: 'APPS_MATCH_GET_PROFILES_FAILED',
type: 'error',
});
} }
} }
async handleInitialize(src: number) { async handleSaveLikes(reqObj: PromiseRequest<Like[]>, resp: PromiseEventResp<boolean>) {
const identifier = PlayerService.getIdentifier(src); const identifier = PlayerService.getIdentifier(reqObj.source);
matchLogger.debug(`Initializing match for identifier: ${identifier}`); matchLogger.debug(`Saving likes for identifier ${identifier}`);
await this.dispatchPlayerProfile(identifier, src); try {
await this.dispatchProfiles(identifier, src); await this.matchDB.saveLikes(identifier, reqObj.data);
await this.matchDB.updateLastActive(identifier); } catch (e) {
matchLogger.error(`Failed to save likes, ${e.message}`);
resp({ status: 'error', errorMsg: 'DB_ERROR' });
}
try {
const newMatches = await this.matchDB.findNewMatches(identifier, reqObj.data);
if (newMatches.length > 0) {
resp({ status: 'ok', data: true });
}
} catch (e) {
matchLogger.error(`Failed to find new matches, ${e.message}`);
resp({ status: 'error', errorMsg: 'DB_ERROR' });
}
} }
async handleCreateMyProfile(src: number, profile: Profile) { async handleGetMatches(reqObj: PromiseRequest<void>, resp: PromiseEventResp<FormattedMatch[]>) {
const identifier = PlayerService.getIdentifier(src); const identifier = PlayerService.getIdentifier(reqObj.source);
try {
const matchedProfiles = await this.matchDB.findAllMatches(identifier);
const formattedMatches = matchedProfiles.map(formatMatches);
resp({ status: 'ok', data: formattedMatches });
} catch (e) {
matchLogger.error(`Failed to retrieve matches, ${e.message}`);
resp({ status: 'error', errorMsg: 'DB_ERROR' });
}
}
async handleCreateMyProfile(
reqObj: PromiseRequest<Profile>,
resp: PromiseEventResp<FormattedProfile>,
) {
const identifier = PlayerService.getIdentifier(reqObj.source);
const profile = reqObj.data;
matchLogger.debug(`Creating profile for identifier: ${identifier}`); matchLogger.debug(`Creating profile for identifier: ${identifier}`);
matchLogger.debug(profile); matchLogger.debug(profile);
@@ -57,18 +96,22 @@ class _MatchService {
} }
const newProfile = await this.matchDB.createProfile(identifier, profile); const newProfile = await this.matchDB.createProfile(identifier, profile);
emitNet(MatchEvents.CREATE_MY_PROFILE_SUCCESS, src, newProfile); const formattedProfile = formatProfile(newProfile);
resp({ status: 'ok', data: formattedProfile });
} catch (e) { } catch (e) {
matchLogger.error(`Failed to update profile for identifier ${identifier}, ${e.message}`); matchLogger.error(`Failed to update profile for identifier ${identifier}, ${e.message}`);
emitNet(MatchEvents.CREATE_MY_PROFILE_FAILED, src, { resp({ status: 'error', errorMsg: 'DB_ERROR' });
message: 'APPS_MATCH_CREATE_PROFILE_FAILED',
type: 'error',
});
} }
} }
async handleUpdateMyProfile(src: number, profile: Profile) { async handleUpdateMyProfile(
const identifier = PlayerService.getIdentifier(src); reqObj: PromiseRequest<Profile>,
resp: PromiseEventResp<FormattedProfile>,
) {
const identifier = PlayerService.getIdentifier(reqObj.source);
const profile = reqObj.data;
matchLogger.debug(`Updating profile for identifier: ${identifier}`); matchLogger.debug(`Updating profile for identifier: ${identifier}`);
matchLogger.debug(profile); matchLogger.debug(profile);
@@ -78,57 +121,38 @@ class _MatchService {
} }
const updatedProfile = await this.matchDB.updateProfile(identifier, profile); const updatedProfile = await this.matchDB.updateProfile(identifier, profile);
emitNet(MatchEvents.UPDATE_MY_PROFILE_SUCCESS, src, updatedProfile); const formattedProfile = formatProfile(updatedProfile);
resp({ status: 'ok', data: formattedProfile });
} catch (e) { } catch (e) {
matchLogger.error(`Failed to update profile for identifier ${identifier}, ${e.message}`); matchLogger.error(`Failed to update profile for identifier ${identifier}, ${e.message}`);
emitNet(MatchEvents.UPDATE_MY_PROFILE_FAILED, src, { resp({ status: 'error', errorMsg: 'DB_ERROR' });
message: 'APPS_MATCH_UPDATE_PROFILE_FAILED',
type: 'error',
});
} }
} }
async handleSaveLikes(src: number, likes: Like[]) { async dispatchPlayerProfile(identifier: string): Promise<FormattedProfile> {
const identifier = PlayerService.getIdentifier(src);
matchLogger.debug(`Saving likes for identifier ${identifier}`);
try { try {
await this.matchDB.saveLikes(identifier, likes); const profile = await this.matchDB.getOrCreateProfile(identifier);
return formatProfile(profile);
} catch (e) { } catch (e) {
matchLogger.error(`Failed to save likes, ${e.message}`); matchLogger.error(`Failed to get player profile, ${e.message}`);
emitNet(MatchEvents.SAVE_LIKES_FAILED, src, {
message: 'APPS_MATCH_SAVE_LIKES_FAILED',
type: 'error',
});
}
try {
const newMatches = await this.matchDB.findNewMatches(identifier, likes);
if (newMatches.length > 0) {
emitNet(MatchEvents.NEW_MATCH, src, {
message: 'APPS_MATCH_NEW_LIKE_FOUND',
type: 'info',
});
}
} catch (e) {
matchLogger.error(`Failed to find new matches, ${e.message}`);
} }
} }
async handleGetMatches(src: number) { async dispatchProfiles(identifier: string): Promise<FormattedProfile[]> {
const identifier = PlayerService.getIdentifier(src);
try { try {
const matchedProfiles = await this.matchDB.findAllMatches(identifier); const profiles = await this.matchDB.getPotentialProfiles(identifier);
emitNet(MatchEvents.GET_MATCHES_SUCCESS, src, matchedProfiles); return profiles.map(formatProfile);
} catch (e) { } catch (e) {
matchLogger.error(`Failed to retrieve matches, ${e.message}`); matchLogger.error(`Failed to retrieve profiles, ${e.message}`);
emitNet(MatchEvents.GET_MATCHES_FAILED, src, {
message: 'APPS_MATCH_GET_MATCHES_FAILED',
type: 'error',
});
} }
} }
async handleInitialize(src: number) {
const identifier = PlayerService.getIdentifier(src);
matchLogger.debug(`Initializing match for identifier: ${identifier}`);
await this.matchDB.updateLastActive(identifier);
}
} }
const MatchService = new _MatchService(); const MatchService = new _MatchService();
+20
View File
@@ -1,3 +1,23 @@
import { mainLogger } from '../sv_logger'; import { mainLogger } from '../sv_logger';
import { FormattedMatch, FormattedProfile, Match, Profile } from '../../../typings/match';
import dayjs from 'dayjs';
export const matchLogger = mainLogger.child({ module: 'match' }); export const matchLogger = mainLogger.child({ module: 'match' });
export function formatProfile(profile: Profile): FormattedProfile | null {
return {
...profile,
tagList: profile.tags.split(',').filter((t) => t), // remove any empty tags
lastActiveFormatted: dayjs.unix(profile.lastActive).toString(),
viewed: false,
};
}
export function formatMatches(match: Match): FormattedMatch | null {
return {
...match,
tagList: match.tags.split(',').filter((t) => t), // remove any empty tags
lastActiveFormatted: dayjs.unix(match.lastActive).toString(),
matchedAtFormatted: dayjs.unix(match.matchedAt).toString(),
};
}
+422 -438
View File
File diff suppressed because it is too large. Load diff