Skip to content

Commit

Permalink
feat(game/server): new router experiments
Browse files Browse the repository at this point in the history
  • Loading branch information
itschip committed Jan 29, 2024
1 parent 3db8f03 commit 5d6a7b9
Show file tree
Hide file tree
Showing 11 changed files with 61 additions and 11 deletions.
1 change: 1 addition & 0 deletions apps/game/client/cl_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,7 @@ export const RegisterNuiProxy = (event: string) => {
if (!global.isPlayerLoaded) await playerLoaded();
try {
const res = await ClUtils.emitNetPromise(event, data);

cb(res);
} catch (e) {
console.error('Error encountered while listening to resp. Error:', e);
Expand Down
4 changes: 4 additions & 0 deletions apps/game/client/router-client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import { createClient } from '@core/router';
import { AppRouter } from '../server/router-server';

export const client = createClient<AppRouter>();
1 change: 1 addition & 0 deletions apps/game/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"lint": "eslint . --ext .ts"
},
"dependencies": {
"@core/router": "workspace:^",
"@discordjs/collection": "^0.2.4",
"@npwd/config": "workspace:*",
"@npwd/database": "workspace:*",
Expand Down
10 changes: 10 additions & 0 deletions apps/game/server/notes/notes.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,16 @@ import { BeforeDBNote, DeleteNoteDTO, NoteItem, NotesEvents } from '@typings/not
import NotesService from './notes.service';
import { notesLogger } from './notes.utils';
import { onNetPromise } from '../lib/PromiseNetEvents/onNetPromise';
import { eventProcedure, router } from '../router-server';

export const notesRouter = router({
addNote: eventProcedure(NotesEvents.ADD_NOTE, async (reqObj, resp) => {
NotesService.handleAddNote(reqObj, resp).catch((e) => {
notesLogger.error(`Error occured in add note event (${reqObj.source}), Error: ${e.message}`);
resp({ status: 'error', errorMsg: 'UNKNOWN_ERROR' });
});
}),
});

onNetPromise<BeforeDBNote, NoteItem>(NotesEvents.ADD_NOTE, (reqObj, resp) => {
NotesService.handleAddNote(reqObj, resp).catch((e) => {
Expand Down
13 changes: 13 additions & 0 deletions apps/game/server/router-server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { initRouter } from '@core/router';
import { notesRouter } from './notes/notes.controller';

const t = initRouter.create();

export const router = t.router;
export const eventProcedure = t.eventProcedure;

const appRouter = router({
notes: notesRouter,
});

export type AppRouter = typeof appRouter;
2 changes: 1 addition & 1 deletion config.default.json
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@
},
"defaultContacts": [],
"disabledApps": [],
"apps": [],
"apps": ["mockapp"],
"voiceMessage": {
"enabled": false,
"authorizationHeader": "Authorization",
Expand Down
4 changes: 3 additions & 1 deletion core/router/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
"name": "@core/router",
"version": "1.0.0",
"description": "",
"main": "index.js",
"main": "./dist/index.js",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"scripts": {
"build": "tsup src/index.ts --format cjs,esm --dts --minify --clean --sourcemap"
},
Expand Down
6 changes: 5 additions & 1 deletion core/router/src/example.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,14 @@ type PlayerData = {
amount: number;
};

const appRouter = router({
const playerRouter = router({
giveMoney: eventProcedure('giveMoney', async (data: PlayerData) => {
console.log('Giving money to player: ', data.playerId, data.amount);
}),
});

const appRouter = router({
player: playerRouter,
});

export type AppRouter = typeof appRouter;
6 changes: 2 additions & 4 deletions core/router/src/example_client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,5 @@ import { AppRouter } from './example';

const client = createClient<AppRouter>();

client.giveMoney.emitNet({
amount: 100,
playerId: 1,
});
client.player.giveMoney.emit({ playerId: 1, amount: 100 });
client.player.giveMoney.emitNet({ playerId: 1, amount: 100 });
22 changes: 18 additions & 4 deletions core/router/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ type FunctionWithEmit<T extends RouterFunction> = {
emit: T;
emitNet: T;
};
type NestedRouter = Record<string, FunctionWithEmit<RouterFunction>>;
type RouterFunctions = Record<string, FunctionWithEmit<RouterFunction> | NestedRouter>;

function createdFunctionWithEmit<T extends RouterFunction>(fn: T): FunctionWithEmit<T> {
return {
Expand All @@ -23,11 +25,23 @@ function eventProcedure<T extends RouterFunction>(event: string, callback: T): F
return createdFunctionWithEmit(callback);
}

type RouterFunctions = Record<string, FunctionWithEmit<RouterFunction>>;

function createRouter() {
return function <T extends RouterFunctions>(routes: T): T {
return routes;
// Implementation to handle both individual route functions and nested routers
const processedRoutes: Partial<RouterFunctions> = {};

for (const key in routes) {
const route = routes[key];
if (typeof route === 'function' || 'emit' in route || 'emitNet' in route) {
// If it's a function or a wrapped function, add it directly
processedRoutes[key] = route;
} else {
// If it's a nested router, merge its routes
Object.assign(processedRoutes, route);
}
}

return processedRoutes as T;
};
}

Expand All @@ -43,7 +57,7 @@ class RouterBuilder {
export const initRouter = new RouterBuilder();

export function createClient<
T extends Record<string, FunctionWithEmit<(...args: any[]) => Promise<any>>>,
T extends Record<string, FunctionWithEmit<(...args: any[]) => Promise<any>> | NestedRouter>,
>(): T {
return {} as T;
}
3 changes: 3 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 5d6a7b9

Please sign in to comment.