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 {
@@ -9,8 +8,6 @@ const {
throwUnexpectedConfigError,
} = require('@craco/craco');
const SentryCliPlugin = require('@sentry/webpack-plugin');
const throwError = (message) =>
throwUnexpectedConfigError({
packageName: 'craco',
@@ -22,28 +19,6 @@ const throwError = (message) =>
module.exports = {
webpack: {
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'));
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 { useApps } from './os/apps/hooks/useApps';
import { useTwitterService } from './apps/twitter/hooks/useTwitterService';
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';
@@ -31,6 +30,7 @@ import PhoneWrapper from './PhoneWrapper';
import dayjs from 'dayjs';
import DefaultConfig from '../../config.json';
import { TopLevelErrorComponent } from './ui/components/TopLevelErrorComponent';
import { useConfig } from './os/phone/hooks/useConfig';
function Phone() {
const { t, i18n } = useTranslation();
@@ -59,11 +59,12 @@ function Phone() {
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useConfig();
useKeyboardService();
usePhoneService();
useSimcardService();
useTwitterService();
useMatchService();
useMarketplaceService();
useBankService();
useMessagesService();
@@ -49,16 +49,6 @@ export const TransactionList = () => {
</div>
</div>
))}
<TablePagination
rowsPerPageOptions={[3, 5]}
className={classes.pagination}
component="div"
count={transactionList.length}
rowsPerPage={rowsPerPage}
page={page}
onChangePage={handleChangePage}
onChangeRowsPerPage={handleChangeRowsPerPage}
/>
</div>
</div>
);
+6 -135
View File
@@ -1,29 +1,16 @@
import React, { useState, useEffect } from 'react';
import { Route } from 'react-router-dom';
import React, { useState } from 'react';
import { AppWrapper } from '../../../ui/components';
import { AppTitle } from '../../../ui/components/AppTitle';
import { AppContent } from '../../../ui/components/AppContent';
import { useApp } from '../../../os/apps/hooks/useApps';
import InjectDebugData from '../../../os/debug/InjectDebugData';
import { MatchThemeProvider } from '../providers/MatchThemeProvider';
import { useNuiRequest } from 'fivem-nui-react-lib';
import MatchBottomNavigation from '../components/BottomNavigation';
import MatchPage from './views/MatchPage';
import ProfileEditor from './views/ProfileEditor';
import MatchList from './views/MatchList';
import { MatchEvents } from '../../../../../typings/match';
import { useProfile } from '../hooks/useProfile';
import MatchContainer from './MatchContainer';
export const MatchApp = () => {
const Nui = useNuiRequest();
const match = useApp('MATCH');
const [activePage, setActivePage] = useState(0);
const { noProfileExists } = useProfile();
useEffect(() => {
Nui.send(MatchEvents.INITIALIZE);
}, [Nui]);
const handlePageChange = (e, page) => setActivePage(page);
@@ -31,127 +18,11 @@ export const MatchApp = () => {
<MatchThemeProvider>
<AppWrapper id="contact-app">
<AppTitle app={match} />
{noProfileExists ? (
<AppContent>
<ProfileEditor />
</AppContent>
) : (
<>
<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} />
</>
)}
<AppContent>
<MatchContainer />
</AppContent>
<MatchBottomNavigation activePage={activePage} handleChange={handlePageChange} />
</AppWrapper>
</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';
const useStyles = makeStyles({
root: {},
tags: {
position: 'absolute',
bottom: '40%',
@@ -1,7 +1,6 @@
import React, { useState } from 'react';
import { makeStyles } from '@material-ui/core/styles';
import { useTranslation } from 'react-i18next';
import { useNuiRequest } from 'fivem-nui-react-lib';
import {
Profile as IProfile,
FormattedProfile,
@@ -13,6 +12,10 @@ import { Card } from '@material-ui/core';
import Profile from './Profile';
import { usePhone } from '../../../../os/phone/hooks/usePhone';
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({
root: {
@@ -39,10 +42,11 @@ interface IProps {
}
export function ProfileForm({ profile, showPreview }: IProps) {
const Nui = useNuiRequest();
const classes = useStyles();
const { t } = useTranslation();
const { ResourceConfig } = usePhone();
const { addAlert } = useSnackbar();
const setMyProfile = useSetMyProfile();
// note that this assumes we are defensively checking
// 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(','),
};
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')} />;
}
@@ -108,6 +126,7 @@ export function ProfileForm({ profile, showPreview }: IProps) {
value={update.bio}
handleChange={setBio}
multiline
maxLength={250}
/>
<ProfileField
label={t('APPS_MATCH_EDIT_PROFILE_LOCATION')}
@@ -118,6 +137,7 @@ export function ProfileForm({ profile, showPreview }: IProps) {
label={t('APPS_MATCH_EDIT_PROFILE_JOB')}
value={update.job}
handleChange={setJob}
maxLength={50}
/>
<ProfileField label={t('APPS_MATCH_EDIT_PROFILE_TAGS')} value={tags} handleChange={setTags} />
<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 { Box, makeStyles } from '@material-ui/core';
import { useMatches } from '../../hooks/useMatches';
import Loader from '../Loader';
import PageText from '../PageText';
import Match from '../matches/Match';
import { useNuiRequest } from 'fivem-nui-react-lib';
import { MatchEvents } from '../../../../../../typings/match';
import { useMatches } from '../../hooks/useMatches';
const useStyles = makeStyles({
root: {
@@ -15,30 +13,13 @@ const useStyles = makeStyles({
},
});
const MINIMUM_LOAD_TIME = 1500;
function MatchList() {
const Nui = useNuiRequest();
const classes = useStyles();
const { t } = useTranslation();
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 (!loaded || !matches) return <Loader />;
if (!matches) return <Loader />;
if (matches.length === 0) return <PageText text={t('APPS_MATCH_NO_MATCHES')} />;
return (
@@ -7,6 +7,7 @@ import { useProfiles } from '../../hooks/useProfiles';
import Loader from '../Loader';
import PageText from '../PageText';
import ActiveProfile from '../ActiveProfile';
import { useMatchActions } from '../../hooks/useMatchActions';
const useStyles = makeStyles({
root: {
@@ -23,7 +24,8 @@ const MINIMUM_LOAD_TIME = 1250;
const MatchPage = () => {
const classes = useStyles();
const { t } = useTranslation();
const { profiles, error, activeProfile, setViewed } = useProfiles();
const { profiles, error, activeProfile } = useProfiles();
const { setViewed } = useMatchActions();
const [loaded, setLoaded] = useState(false);
useEffect(() => {
@@ -2,10 +2,9 @@ import React, { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { makeStyles } from '@material-ui/core/styles';
import { Box, FormControlLabel, Switch } from '@material-ui/core';
import { useProfile } from '../../hooks/useProfile';
import Loader from '../Loader';
import ProfileForm from '../profile/ProfileForm';
import { useProfile } from '../../hooks/useProfile';
const useStyles = makeStyles({
root: {
+75 -6
View File
@@ -1,18 +1,55 @@
import { atom } from 'recoil';
import { FormattedMatch, FormattedProfile } from '../../../../../typings/match';
import { atom, selector, useRecoilState, useRecoilValue, useSetRecoilState } from 'recoil';
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 = {
profiles: atom<FormattedProfile[]>({
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',
default: false,
}),
matches: atom<FormattedMatch[]>({
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>({
key: 'errorLoadingMatches',
@@ -20,10 +57,42 @@ export const matchState = {
}),
myProfile: atom<FormattedProfile | null>({
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>({
key: 'noProfileExists',
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 { matchState } from './state';
import { FormattedMatch } from '../../../../../typings/match';
interface IUseMatches {
interface UseMatchProps {
matches: FormattedMatch[];
setMatches: (matches: FormattedMatch[]) => void;
error: boolean;
}
export const useMatches = (): IUseMatches => {
const matches = useRecoilValue<FormattedMatch[]>(matchState.matches);
export const useMatches = (): UseMatchProps => {
const [matches, setMatches] = useFormattedMatches();
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 { matchState } from './state';
import { useMyProfile, useProfileExists } from './state';
import { FormattedProfile } from '../../../../../typings/match';
interface IUseProfiles {
interface UseProfileProps {
profile: FormattedProfile;
setProfile: (profile: FormattedProfile) => void;
noProfileExists: boolean;
setNoProfileExists: (exists: boolean) => void;
}
export const useProfile = (): IUseProfiles => {
const [profile, setProfile] = useRecoilState<FormattedProfile>(matchState.myProfile);
const noProfileExists = useRecoilValue(matchState.noProfileExists);
return { profile, setProfile, noProfileExists };
export const useProfile = (): UseProfileProps => {
const [profile, setProfile] = useMyProfile();
const [noProfileExists, setNoProfileExists] = useProfileExists();
return { profile, setProfile, noProfileExists, setNoProfileExists };
};
+7 -21
View File
@@ -1,34 +1,20 @@
import { useRecoilState, useRecoilValue } from 'recoil';
import { matchState } from './state';
import { useRecoilValue } from 'recoil';
import { matchState, useFormattedProfiles } from './state';
import { FormattedProfile, MatchEvents } from '../../../../../typings/match';
import { useNuiRequest } from 'fivem-nui-react-lib';
import { FormattedProfile } from '../../../../../typings/match';
interface IUseProfiles {
interface UseProfilesProps {
profiles: FormattedProfile[];
activeProfile: FormattedProfile | null;
setViewed: (index: number, liked: boolean) => void;
error: boolean;
}
export const useProfiles = (): IUseProfiles => {
const Nui = useNuiRequest();
const [profiles, setProfiles] = useRecoilState(matchState.profiles);
export const useProfiles = (): UseProfilesProps => {
const [profiles] = useFormattedProfiles();
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 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 { SettingsApp } from '../../../apps/settings/components/SettingsApp';
import { MessagesApp } from '../../../apps/messages/components/MessagesApp';
import { MatchApp } from '../../../apps/match/components/MatchApp';
import { TwitterApp } from '../../../apps/twitter/components/TwitterApp';
import { ExampleApp } from '../../../apps/example/components/ExampleApp';
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 { INotificationIcon } from '../../notifications/providers/NotificationsProvider';
import { BrowserApp } from '../../../apps/browser/components/BrowserApp';
import { MatchApp } from '../../../apps/match/components/MatchApp';
export interface IAppConfig {
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 _handleChange = (e) => handleChange(e.target.value);
@@ -24,6 +24,9 @@ function ProfileField({ label, value, handleChange, allowChange, multiline, inpu
value={value}
onChange={_handleChange}
disabled={!allowChange}
inputProps={{
maxLength: maxLength,
}}
multiline={multiline}
inputRef={inputRef}
/>
@@ -33,6 +36,7 @@ function ProfileField({ label, value, handleChange, allowChange, multiline, inpu
ProfileField.defaultProps = {
allowChange: true,
maxLength: 200,
multiline: false,
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' });
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);
+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() {
emitNet(MessageEvents.FETCH_MESSAGE_GROUPS);
emitNet(TwitterEvents.GET_OR_CREATE_PROFILE);
sendMessage('PHONE', PhoneEvents.SET_CONFIG, config);
}
onNet(PhoneEvents.ON_INIT, () => {
+8 -52
View File
@@ -1,53 +1,9 @@
import { Like, Profile, MatchEvents } from '../../typings/match';
import { sendMatchEvent } from '../utils/messages';
import { MatchEvents } from '../../typings/match';
import { RegisterNuiProxy } from './cl_utils';
/**
* Many events that are just statuses are passed directly from
* the server to NUI and the client is just acting as a middle man.
* For those cases this function allows us to simply transfer all the
* data associated with the event.
* @param eventName - event we are propagating
*/
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);
});
RegisterNuiProxy(MatchEvents.GET_PROFILES);
RegisterNuiProxy(MatchEvents.GET_MY_PROFILE);
RegisterNuiProxy(MatchEvents.GET_MATCHES);
RegisterNuiProxy(MatchEvents.SAVE_LIKES);
RegisterNuiProxy(MatchEvents.CREATE_MY_PROFILE);
RegisterNuiProxy(MatchEvents.UPDATE_MY_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 { getSource } from '../utils/miscUtils';
import { matchLogger } from './match.utils';
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, () => {
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) {
const warning =
`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 { Like, MatchEvents, Profile } from '../../../typings/match';
import {
FormattedMatch,
FormattedProfile,
Like,
MatchEvents,
Profile,
} from '../../../typings/match';
import PlayerService from '../players/player.service';
import { PromiseEventResp, PromiseRequest } from '../utils/PromiseNetEvents/promise.types';
class _MatchService {
private readonly matchDB: _MatchDB;
constructor() {
this.matchDB = MatchDB;
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 {
const profile = await this.matchDB.getOrCreateProfile(identifier);
emitNet(MatchEvents.GET_MY_PROFILE_SUCCESS, source, profile);
const profiles = await this.dispatchProfiles(identifier);
resp({ status: 'ok', data: profiles });
} catch (e) {
matchLogger.error(`Failed to get player profile, ${e.message}`);
emitNet(MatchEvents.GET_MY_PROFILE_FAILED, source, {
message: 'APPS_MATCH_GET_MY_PROFILE_FAILED',
type: 'error',
});
matchLogger.error(`Error in handleGetProfiles, ${e.message}`);
resp({ status: 'error', errorMsg: 'DB_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 {
const profiles = await this.matchDB.getPotentialProfiles(identifier);
emitNet(MatchEvents.GET_PROFILES_SUCCESS, source, profiles);
const profile = await this.dispatchPlayerProfile(identifier);
resp({ status: 'ok', data: profile });
} catch (e) {
matchLogger.error(`Failed to retrieve profiles, ${e.message}`);
emitNet(MatchEvents.GET_PROFILES_FAILED, source, {
message: 'APPS_MATCH_GET_PROFILES_FAILED',
type: 'error',
});
matchLogger.error(`Error in handleGetMyProfile, ${e.message}`);
resp({ status: 'error', errorMsg: 'DB_ERROR' });
}
}
async handleInitialize(src: number) {
const identifier = PlayerService.getIdentifier(src);
matchLogger.debug(`Initializing match for identifier: ${identifier}`);
async handleSaveLikes(reqObj: PromiseRequest<Like[]>, resp: PromiseEventResp<boolean>) {
const identifier = PlayerService.getIdentifier(reqObj.source);
matchLogger.debug(`Saving likes for identifier ${identifier}`);
await this.dispatchPlayerProfile(identifier, src);
await this.dispatchProfiles(identifier, src);
await this.matchDB.updateLastActive(identifier);
try {
await this.matchDB.saveLikes(identifier, reqObj.data);
} 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) {
const identifier = PlayerService.getIdentifier(src);
async handleGetMatches(reqObj: PromiseRequest<void>, resp: PromiseEventResp<FormattedMatch[]>) {
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(profile);
@@ -57,18 +96,22 @@ class _MatchService {
}
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) {
matchLogger.error(`Failed to update profile for identifier ${identifier}, ${e.message}`);
emitNet(MatchEvents.CREATE_MY_PROFILE_FAILED, src, {
message: 'APPS_MATCH_CREATE_PROFILE_FAILED',
type: 'error',
});
resp({ status: 'error', errorMsg: 'DB_ERROR' });
}
}
async handleUpdateMyProfile(src: number, profile: Profile) {
const identifier = PlayerService.getIdentifier(src);
async handleUpdateMyProfile(
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(profile);
@@ -78,57 +121,38 @@ class _MatchService {
}
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) {
matchLogger.error(`Failed to update profile for identifier ${identifier}, ${e.message}`);
emitNet(MatchEvents.UPDATE_MY_PROFILE_FAILED, src, {
message: 'APPS_MATCH_UPDATE_PROFILE_FAILED',
type: 'error',
});
resp({ status: 'error', errorMsg: 'DB_ERROR' });
}
}
async handleSaveLikes(src: number, likes: Like[]) {
const identifier = PlayerService.getIdentifier(src);
matchLogger.debug(`Saving likes for identifier ${identifier}`);
async dispatchPlayerProfile(identifier: string): Promise<FormattedProfile> {
try {
await this.matchDB.saveLikes(identifier, likes);
const profile = await this.matchDB.getOrCreateProfile(identifier);
return formatProfile(profile);
} catch (e) {
matchLogger.error(`Failed to save likes, ${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}`);
matchLogger.error(`Failed to get player profile, ${e.message}`);
}
}
async handleGetMatches(src: number) {
const identifier = PlayerService.getIdentifier(src);
async dispatchProfiles(identifier: string): Promise<FormattedProfile[]> {
try {
const matchedProfiles = await this.matchDB.findAllMatches(identifier);
emitNet(MatchEvents.GET_MATCHES_SUCCESS, src, matchedProfiles);
const profiles = await this.matchDB.getPotentialProfiles(identifier);
return profiles.map(formatProfile);
} catch (e) {
matchLogger.error(`Failed to retrieve matches, ${e.message}`);
emitNet(MatchEvents.GET_MATCHES_FAILED, src, {
message: 'APPS_MATCH_GET_MATCHES_FAILED',
type: 'error',
});
matchLogger.error(`Failed to retrieve profiles, ${e.message}`);
}
}
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();
+20
View File
@@ -1,3 +1,23 @@
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 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