refactor(server/marketplace): Refactor to use promise events

This commit is contained in:
Taso committed 2021-06-08 15:46:57 -04:00
1 parent 4afa9c691b
commit 3df2f88759
9 files changed
+160 -134

No files matched your search

@@ -51,21 +51,21 @@ export const ListingActions: React.FC<MarketplaceListing> = ({ children, ...list
}; };
const handleReportListing = () => { const handleReportListing = () => {
fetchNui<MarketplaceActionResp>(MarketplaceEvents.DELETE_LISTING, listing).then( fetchNui<MarketplaceActionResp>(MarketplaceEvents.REPORT_LISTING, {
({ err, errMsg }) => { listingId: listing.id,
if (err) { }).then(({ err, errMsg }) => {
return addAlert({ if (err) {
message: t(errMsg), return addAlert({
type: 'error', message: t(errMsg),
}); type: 'error',
}
addAlert({
message: t('APPS_MARKETPLACE_REPORT_LISTING_SUCCESS'),
type: 'success',
}); });
}, }
);
addAlert({
message: t('APPS_MARKETPLACE_REPORT_LISTING_SUCCESS'),
type: 'success',
});
});
}; };
const handleCall = () => { const handleCall = () => {
@@ -56,7 +56,7 @@ export const ListingForm = () => {
}).then(({ err, errMsg }) => { }).then(({ err, errMsg }) => {
if (err) { if (err) {
return addAlert({ return addAlert({
message: t(errMsg), message: t('errMsg'),
type: 'error', type: 'error',
}); });
} }
+6 -2
View File
@@ -1,5 +1,9 @@
import { atom, selector, useRecoilValue, useSetRecoilState } from 'recoil'; import { atom, selector, useRecoilValue, useSetRecoilState } from 'recoil';
import { MarketplaceEvents, MarketplaceListing } from '../../../../../typings/marketplace'; import {
MarketplaceEvents,
MarketplaceFetchResp,
MarketplaceListing,
} from '../../../../../typings/marketplace';
import { fetchNui } from '../../../utils/fetchNui'; import { fetchNui } from '../../../utils/fetchNui';
const defaultData: MarketplaceListing[] = [ const defaultData: MarketplaceListing[] = [
@@ -30,7 +34,7 @@ const listingState = atom<MarketplaceListing[]>({
key: 'defaultListings', key: 'defaultListings',
get: async () => { get: async () => {
try { try {
return await fetchNui<MarketplaceListing[]>(MarketplaceEvents.FETCH_LISTING); return (await fetchNui<MarketplaceFetchResp>(MarketplaceEvents.FETCH_LISTING)).data;
} catch (e) { } catch (e) {
if (process.env.NODE_ENV === 'development' && !process.env.REACT_APP_IN_GAME) { if (process.env.NODE_ENV === 'development' && !process.env.REACT_APP_IN_GAME) {
return defaultData; return defaultData;
@@ -23,7 +23,6 @@ export const useMarketplaceService = () => {
const deleteDTO = listing as MarketplaceDeleteDTO; const deleteDTO = listing as MarketplaceDeleteDTO;
return setListings((currVal) => { return setListings((currVal) => {
const arrayPos = currVal.map((item) => item.id).indexOf(deleteDTO.id); const arrayPos = currVal.map((item) => item.id).indexOf(deleteDTO.id);
return [...currVal].splice(arrayPos); return [...currVal].splice(arrayPos);
}); });
} }
+2 -36
View File
@@ -1,47 +1,13 @@
import { MarketplaceEvents, MarketplaceListingBroadcast } from '../../typings/marketplace'; import { MarketplaceEvents, MarketPlaceBroadcastData } from '../../typings/marketplace';
import { RegisterNuiProxy } from './cl_utils'; import { RegisterNuiProxy } from './cl_utils';
import { sendMarketplaceEvent } from '../utils/messages'; import { sendMarketplaceEvent } from '../utils/messages';
// onNet(MarketplaceEvents.SEND_LISTING, (listings: MarketplaceListing[]) => {
// sendMarketplaceEvent(MarketplaceEvents.SEND_LISTING, listings);
// });
RegisterNuiProxy(MarketplaceEvents.FETCH_LISTING); RegisterNuiProxy(MarketplaceEvents.FETCH_LISTING);
RegisterNuiProxy(MarketplaceEvents.ADD_LISTING); RegisterNuiProxy(MarketplaceEvents.ADD_LISTING);
// RegisterNuiCallbackType(MarketplaceEvents.ADD_LISTING);
// on(`__cfx_nui:${MarketplaceEvents.ADD_LISTING}`, (data: MarketplaceListing, cb: Function) => {
// emitNet(MarketplaceEvents.ADD_LISTING, data);
// cb();
// });
RegisterNuiProxy(MarketplaceEvents.DELETE_LISTING); RegisterNuiProxy(MarketplaceEvents.DELETE_LISTING);
RegisterNuiProxy(MarketplaceEvents.REPORT_LISTING); RegisterNuiProxy(MarketplaceEvents.REPORT_LISTING);
onNet(MarketplaceEvents.BROADCAST_EVENT, (broadcastEvent: MarketplaceListingBroadcast) => { onNet(MarketplaceEvents.BROADCAST_EVENT, (broadcastEvent: MarketPlaceBroadcastData) => {
sendMarketplaceEvent(MarketplaceEvents.BROADCAST_EVENT, broadcastEvent); sendMarketplaceEvent(MarketplaceEvents.BROADCAST_EVENT, broadcastEvent);
}); });
// RegisterNuiCallbackType(MarketplaceEvents.DELETE_LISTING);
// on(`__cfx_nui:${MarketplaceEvents.DELETE_LISTING}`, (data: MarketplaceListing, cb: Function) => {
// emitNet(MarketplaceEvents.DELETE_LISTING, data.id);
// cb();
// });
// RegisterNuiCallbackType(MarketplaceEvents.REPORT_LISTING);
// on(`__cfx_nui:${MarketplaceEvents.REPORT_LISTING}`, (data: MarketplaceListing, cb: Function) => {
// emitNet(MarketplaceEvents.REPORT_LISTING, data);
// cb();
// });
// onNet(MarketplaceEvents.ADD_LISTING_SUCCESS, () => {
// emitNet(MarketplaceEvents.FETCH_LISTING);
// });
// onNet(MarketplaceEvents.DELETE_LISTING_SUCCESS, () => {
// emitNet(MarketplaceEvents.FETCH_LISTING);
// });
// onNet(MarketplaceEvents.ACTION_RESULT, (alert: IAlertProps) => {
// sendMarketplaceEvent(MarketplaceEvents.SEND_ALERT, alert);
// });
@@ -1,42 +1,59 @@
import { MarketplaceEvents, MarketplaceListing } from '../../../typings/marketplace'; import {
import { getSource } from '../utils/miscUtils'; MarketplaceEvents,
MarketplaceListingBase,
MarketplaceReportDTO,
} from '../../../typings/marketplace';
import PlayerService from '../players/player.service'; import PlayerService from '../players/player.service';
import { selloutLogger } from './marketplace.utils'; import { selloutLogger } from './marketplace.utils';
import MarketplaceService from './marketplace.service'; import MarketplaceService from './marketplace.service';
import { onNetPromise } from '../utils/PromiseNetEvents/onNetPromise';
import { MarketplaceDeleteDTO } from '../../../typings/marketplace';
onNet(MarketplaceEvents.FETCH_LISTING, async () => { onNetPromise(MarketplaceEvents.FETCH_LISTING, async (reqObj, resp) => {
const src = getSource(); MarketplaceService.handleFetchListings(resp, reqObj.source).catch((e) => {
MarketplaceService.handleFetchListings(src).catch((e) => selloutLogger.error(
selloutLogger.error(`Error occurred in fetch listing event (${src}), Error: ${e.message}`), `Error occurred in fetch listing event (${reqObj.source}), Error: ${e.message}`,
); );
resp({ error: true, errorMsg: '`Error occurred in fetch listing event' });
});
}); });
onNet(MarketplaceEvents.ADD_LISTING, async (listing: MarketplaceListing) => { onNetPromise<MarketplaceListingBase>(MarketplaceEvents.ADD_LISTING, async (reqObj, resp) => {
const src = getSource(); const player = PlayerService.getPlayer(reqObj.source);
const Player = PlayerService.getPlayer(src);
MarketplaceService.handleAddListing( MarketplaceService.handleAddListing(
src, {
Player.getFirstName(), src: reqObj.source,
Player.username, name: player.getName(),
Player.getName(), username: player.username,
Player.getPhoneNumber(), number: player.getPhoneNumber(),
listing, listing: reqObj.data,
).catch((e) => identifier: player.getIdentifier(),
selloutLogger.error(`Error occurred in add listing event (${src}), Error: ${e.message}`), },
); resp,
).catch((e) => {
selloutLogger.error(
`Error occurred in add listing event (${reqObj.source}), Error: ${e.message}`,
);
resp({ error: true, errorMsg: 'Error occurred in add listing event' });
});
}); });
onNet(MarketplaceEvents.DELETE_LISTING, async (listingId: number) => { onNetPromise<MarketplaceDeleteDTO>(MarketplaceEvents.DELETE_LISTING, async (reqObj, resp) => {
const src = getSource(); // TODO: Needs a permission check of some sort here eventually
MarketplaceService.handleDeleteListing(src, listingId).catch((e) => MarketplaceService.handleDeleteListing(reqObj, resp).catch((e) => {
selloutLogger.error(`Error occurred in delete listing event (${src}), Error: ${e.message}`), selloutLogger.error(
); `Error occurred in delete listing event (${reqObj.source}), Error: ${e.message}`,
);
resp({ error: true, errorMsg: 'Error occurred in delete listing event' });
});
}); });
onNet(MarketplaceEvents.REPORT_LISTING, async (listing: MarketplaceListing) => { onNetPromise<MarketplaceReportDTO>(MarketplaceEvents.REPORT_LISTING, async (reqObj, resp) => {
const src = getSource(); // TODO: Needs a permission check of some sort here eventually
MarketplaceService.handleReportListing(src, listing).catch((e) => MarketplaceService.handleReportListing(reqObj, resp).catch((e) => {
selloutLogger.error(`Error occurred in report listing event (${src}), Error: ${e.message}`), selloutLogger.error(
); `Error occurred in report listing event (${reqObj.source}), Error: ${e.message}`,
);
resp({ error: true, errorMsg: 'Error occured in report listing event' });
});
}); });
@@ -1,5 +1,6 @@
import { pool } from '../db'; import { pool } from '../db';
import { MarketplaceListing } from '../../../typings/marketplace'; import { MarketplaceListing, MarketplaceListingBase } from '../../../typings/marketplace';
import { ResultSetHeader } from 'mysql2';
export class _MarketplaceDB { export class _MarketplaceDB {
async addListing( async addListing(
@@ -7,12 +8,12 @@ export class _MarketplaceDB {
username: string, username: string,
name: string, name: string,
number: any, number: any,
listing: MarketplaceListing, listing: MarketplaceListingBase,
): Promise<void> { ): Promise<number> {
const query = const query =
'INSERT INTO npwd_marketplace_listings (identifier, username, name, number, title, url, description) VALUES (?, ?, ?, ?, ?, ?, ?)'; 'INSERT INTO npwd_marketplace_listings (identifier, username, name, number, title, url, description) VALUES (?, ?, ?, ?, ?, ?, ?)';
await pool.query(query, [ const [result] = await pool.query(query, [
identifier, identifier,
username, username,
name, name,
@@ -21,6 +22,10 @@ export class _MarketplaceDB {
listing.url, listing.url,
listing.description, listing.description,
]); ]);
const resultCast = result as ResultSetHeader;
return resultCast.insertId;
} }
async fetchListings(): Promise<MarketplaceListing[]> { async fetchListings(): Promise<MarketplaceListing[]> {
@@ -1,9 +1,25 @@
import PlayerService from '../players/player.service'; import PlayerService from '../players/player.service';
import { selloutLogger } from './marketplace.utils'; import { selloutLogger } from './marketplace.utils';
import MarketplaceDB, { _MarketplaceDB } from './marketplace.db'; import MarketplaceDB, { _MarketplaceDB } from './marketplace.db';
import { MarketplaceEvents, MarketplaceListing } from '../../../typings/marketplace'; import {
MarketplaceDeleteDTO,
MarketplaceEvents,
MarketplaceListing,
MarketplaceListingBase,
MarketplaceReportDTO,
} from '../../../typings/marketplace';
import { notesLogger } from '../notes/notes.utils'; import { notesLogger } from '../notes/notes.utils';
import { reportListingToDiscord } from '../discord'; import { reportListingToDiscord } from '../discord';
import { PromiseEventReturnFunc, PromiseRequest } from '../utils/PromiseNetEvents/promise.types';
interface HandleAddListingObj {
src: number;
identifier: string;
username: string;
name: string;
number: any;
listing: MarketplaceListingBase;
}
class _MarketplaceService { class _MarketplaceService {
private readonly marketplaceDB: _MarketplaceDB; private readonly marketplaceDB: _MarketplaceDB;
@@ -14,93 +30,104 @@ class _MarketplaceService {
} }
async handleAddListing( async handleAddListing(
src: number, { listing, src, identifier, number, name, username }: HandleAddListingObj,
identifier: string, resp: PromiseEventReturnFunc,
username: string,
name: string,
number: any,
listing: MarketplaceListing,
): Promise<void> { ): Promise<void> {
selloutLogger.debug('Handling add listing, listing:'); selloutLogger.debug('Handling add listing, listing:');
selloutLogger.debug; selloutLogger.debug(listing);
try { try {
await this.marketplaceDB.addListing(identifier, username, name, number, listing); const listingId = await this.marketplaceDB.addListing(
identifier,
username,
name,
number,
listing,
);
// Respond with success to original source
resp({ status: 'ok' });
emitNet(MarketplaceEvents.ADD_LISTING_SUCCESS, src); const returnObj: MarketplaceListing = {
emitNet(MarketplaceEvents.ACTION_RESULT, src, { id: listingId,
message: 'MARKETPLACE_CREATE_LISTING_SUCCESS', identifier,
type: 'success', name,
}); number,
url: listing.url,
username,
description: listing.description,
title: listing.title,
};
// Broadcast to everyone we are adding a listing
emitNet(MarketplaceEvents.BROADCAST_EVENT, -1, { type: 'ADD', listing: returnObj });
} catch (e) { } catch (e) {
selloutLogger.error(`Failed to add listing ${e.message}`, { selloutLogger.error(`Failed to add listing ${e.message}`, {
source: src, source: src,
}); });
emitNet(MarketplaceEvents.ACTION_RESULT, src, { resp({ err: true, errMsg: 'Failed to create listing' });
message: 'MARKETPLACE_CREATE_LISTING_FAILED',
type: 'error',
});
} }
} }
async handleFetchListings(src: number) { async handleFetchListings(resp: PromiseEventReturnFunc, src: number) {
try { try {
const listings = await this.marketplaceDB.fetchListings(); const listings = await this.marketplaceDB.fetchListings();
emitNet(MarketplaceEvents.SEND_LISTING, src, listings); resp({ data: listings, status: 'ok' });
} catch (e) { } catch (e) {
selloutLogger.error(`Failed to fetch listings, ${e.message}`, { selloutLogger.error(`Failed to fetch listings, ${e.message}`, {
source: src, source: src,
}); });
resp({ err: true, errMsg: 'Failed to fetch listings' });
} }
} }
async handleDeleteListing(src: number, listingId: number): Promise<void> { async handleDeleteListing(
const identifier = PlayerService.getIdentifier(src); reqObj: PromiseRequest<MarketplaceDeleteDTO>,
resp: PromiseEventReturnFunc,
): Promise<void> {
const identifier = PlayerService.getIdentifier(reqObj.source);
try { try {
await this.marketplaceDB.deleteListing(listingId, identifier); await this.marketplaceDB.deleteListing(reqObj.data.id, identifier);
emitNet(MarketplaceEvents.DELETE_LISTING_SUCCESS, src); resp({ status: 'ok' });
emitNet(MarketplaceEvents.ACTION_RESULT, src, {
message: 'MARKETPLACE_DELETE_LISTING_SUCCESS', const returnObj: MarketplaceDeleteDTO = {
type: 'success', id: reqObj.data.id,
}); };
emitNet(MarketplaceEvents.BROADCAST_EVENT, -1, { type: 'DELETE', listing: returnObj });
} catch (e) { } catch (e) {
notesLogger.error(`Error in handleDeleteListing, ${e.message}`); notesLogger.error(`Error in handleDeleteListing, ${e.message}`);
emitNet(MarketplaceEvents.ACTION_RESULT, src, { resp({ error: true, errMsg: 'Error in deleting listing' });
message: 'MARKETPLACE_DELETE_LISTING_FAILED',
type: 'error',
});
} }
} }
async handleReportListing(src: number, listing: MarketplaceListing): Promise<void> { async handleReportListing(
reqObj: PromiseRequest<MarketplaceReportDTO>,
resp: PromiseEventReturnFunc,
): Promise<void> {
try { try {
const rListing = await this.marketplaceDB.getListing(listing.id); const rListing = await this.marketplaceDB.getListing(reqObj.data.id);
const reportExists = await this.marketplaceDB.doesReportExist(listing.id, listing.name); const reportExists = await this.marketplaceDB.doesReportExist(
reqObj.data.id,
rListing.number,
);
const reportingPlayer = GetPlayerName(reqObj.source.toString());
const reportingPlayer = GetPlayerName(src.toString());
if (reportExists) { if (reportExists) {
selloutLogger.error(`This listing has already been reported`); selloutLogger.error(`This listing has already been reported`);
return emitNet(MarketplaceEvents.ACTION_RESULT, src, { resp({ error: true, errorMsg: 'Listing already exists' });
message: 'MARKETPLACE_REPORT_LISTING_FAILED',
type: 'info',
});
} }
await this.marketplaceDB.reportListing(rListing.id, rListing.name); await this.marketplaceDB.reportListing(rListing.id, rListing.name);
await reportListingToDiscord(rListing, reportingPlayer); await reportListingToDiscord(rListing, reportingPlayer);
emitNet(MarketplaceEvents.ACTION_RESULT, src, {
message: 'MARKETPLACE_REPORT_LISTING_SUCCESS',
type: 'success',
});
} catch (e) { } catch (e) {
selloutLogger.error(`Failed to report listing ${e.message}`, { selloutLogger.error(`Failed to report listing ${e.message}`, {
source: src, source: reqObj.source,
}); });
resp({ error: true, errorMsg: 'Failed to report listing' });
} }
} }
} }
+8
View File
@@ -12,6 +12,10 @@ export interface MarketplaceListingBase {
description: string; description: string;
} }
export interface MarketplaceFetchResp extends MarketplaceActionResp {
data: MarketplaceListing[];
}
export interface MarketplaceActionResp { export interface MarketplaceActionResp {
err: boolean; err: boolean;
errMsg?: string; errMsg?: string;
@@ -36,6 +40,10 @@ export interface MarketplaceDeleteDTO {
id: number; id: number;
} }
export interface MarketplaceReportDTO {
id: number;
}
export type MarketPlaceBroadcastData = export type MarketPlaceBroadcastData =
| { | {
type: 'ADD'; type: 'ADD';