### Initialize Prisma Client with Logging Source: https://context7.com/thepawlow/fivem-ts-svelte-boilerplate/llms.txt Initializes the Prisma client for PostgreSQL with full logging enabled. It provides type-safe operations for the Account model and includes examples for creating, finding, and counting accounts. ```typescript import { PrismaClient } from "@prisma/client"; export const PRISMA = new PrismaClient({ log: ["query", "error", "warn", "info"], }); // Prisma schema (prisma/schema/account.prisma) // model Account { // id Int @id @default(autoincrement()) // email String @unique // name String? // password String // createdAt DateTime @default(now()) // updatedAt DateTime @updatedAt // } // Usage examples async function createAccount() { const account = await PRISMA.account.create({ data: { email: "player@example.com", name: "PlayerOne", password: "hashedPassword123" } }); return account; } async function findAccountByEmail(email: string) { return await PRISMA.account.findUnique({ where: { email } }); } async function getPlayerCount() { return await PRISMA.account.count(); } ``` -------------------------------- ### Inversify Dependency Injection Container Setup (TypeScript) Source: https://context7.com/thepawlow/fivem-ts-svelte-boilerplate/llms.txt Demonstrates the setup of Inversify dependency injection containers for both server and client contexts in TypeScript. Each container binds services and controllers, allowing them to be injected where needed. This setup is crucial for managing dependencies across the application. Requires the 'inversify' package. ```typescript // Server container (src/server/container.ts) import { Container } from 'inversify'; import { PlayerController } from "./controllers/PlayerController"; import { LogService } from "../shared/services/LogService"; const container: Container = new Container(); container.bind(LogService).toSelf(); container.bind(PlayerController).toSelf(); export { container }; // Client container (src/client/container.ts) import { Container } from 'inversify'; import { LogService } from "../shared/services/LogService"; import { DebugController } from "./controllers/DebugController"; import { NUIController } from "./controllers/NUIController"; const container: Container = new Container(); container.bind(LogService).toSelf(); container.bind(NUIController).toSelf(); container.bind(DebugController).toSelf(); export { container }; // Retrieving services from container const logger = container.get(LogService); const playerController = container.get(PlayerController); ``` -------------------------------- ### Svelte NUI Component Example (Svelte/TypeScript) Source: https://context7.com/thepawlow/fivem-ts-svelte-boilerplate/llms.txt Demonstrates using the NUIController within a Svelte 5 component for reactive state management and bidirectional communication with the game client. It listens for 'showUI' events and emits a 'NUIControllerCloseUI' event. ```svelte {#if isVisible}

Welcome to the FiveM NUI

{/if} ``` -------------------------------- ### Server-Side Event Handling and Prisma Integration (TypeScript) Source: https://context7.com/thepawlow/fivem-ts-svelte-boilerplate/llms.txt Illustrates server-side event handling in TypeScript for FiveM, including player connection events and resource startup. It demonstrates integrating Prisma for database operations and uses the '@nativewrappers/server' package for native event handling. Requires 'reflect-metadata', 'inversify', '@nativewrappers/server', and 'prisma'. ```typescript import 'reflect-metadata'; import { container } from "./container"; import { PlayerController } from "./controllers/PlayerController"; import { LogService } from "../shared/services/LogService"; import { Events } from "@nativewrappers/server"; import { PRISMA } from './DBContext'; const logger = container.get(LogService); const playerController = container.get(PlayerController); // Handle player connection events Events.on("playerConnecting", (name: string) => { logger.log(`Player connected with name ${name}`); }); Events.on("playerDisconnected", (name: string) => { logger.log(`Player disconnected with name ${name}`); }); // Server resource start event with database check Events.on("onServerResourceStart", async (resourceName: string) => { if (resourceName !== GetCurrentResourceName()) return; try { await PRISMA.$connect(); logger.log('Prisma client is connected'); const playersRegistered = await PRISMA.account.count(); logger.log(`Total registered players: ${playersRegistered}`); } catch (error) { logger.log(`Error connecting to Prisma - Error: ${error}`); } finally { await PRISMA.$disconnect(); } logger.log("Server started..."); }); ``` -------------------------------- ### FiveM Resource Manifest (Lua) Source: https://context7.com/thepawlow/fivem-ts-svelte-boilerplate/llms.txt Configures a FiveM resource, specifying the fx_version, game, Node.js version, resource metadata, client/server script entry points, NUI page, and included files. ```lua fx_version 'bodacious' game 'gta5' node_version '22' name 'fivem-ts-svelte-boilerplate' description 'A FiveM Boilerplate using TypeScript Client- / Serverside and Svelte for UI' author 'ThePawlow' url 'https://github.com/ThePawlow/fivem-ts-svelte-boilerplate' client_script 'client/main.js' server_script 'server/main.js' ui_page 'nui/index.html' files { 'nui/index.html', 'nui/assets/*.js', 'nui/assets/*.css' } ``` -------------------------------- ### Docker Compose for FiveM Server and PostgreSQL Source: https://context7.com/thepawlow/fivem-ts-svelte-boilerplate/llms.txt Defines the Docker services for running a FiveM server and a PostgreSQL database using docker-compose. It includes multi-stage build for the server, health checks for the database, and network configuration. ```yaml # docker-compose.yaml services: server: depends_on: db: condition: service_healthy build: context: . dockerfile: Dockerfile container_name: cfx ports: - "30120:30120" - "30120:30120/udp" env_file: - .env networks: - fivem-network db: image: postgres:16.8-alpine3.20 restart: always healthcheck: test: ["CMD-SHELL", "pg_isready -U access_user -d fivem"] interval: 5s timeout: 2s retries: 20 environment: POSTGRES_DB: fivem POSTGRES_USER: access_user POSTGRES_PASSWORD: example volumes: - postgres_data:/var/lib/postgresql/data networks: - fivem-network # Build and run commands # pnpm install # pnpm run build # docker compose up --build ``` -------------------------------- ### Debug Emit Event in Browser with NUIController Source: https://github.com/thepawlow/fivem-ts-svelte-boilerplate/blob/main/frontend-doc.md Simulates emitting an event in the browser environment, useful for testing the `emit` functionality during frontend development. This helps in verifying that the data structure and event names are correct before deploying to the FiveM client. ```typescript NUIController.emit('debugEmit', { success: true }); ``` -------------------------------- ### Debug Event Listener in Browser with NUIController Source: https://github.com/thepawlow/fivem-ts-svelte-boilerplate/blob/main/frontend-doc.md Allows simulating NUI event reception in a browser environment for debugging purposes. You can specify mock data and a delay before the event is triggered, aiding in frontend development without needing the game client. ```typescript NUIController.on('debugEvent', (data) => { console.log('Debug event received:', data); // { test : true } }, { data: { test: true }, delay: 1000 }); ``` -------------------------------- ### Emit Event to Server with NUIController Source: https://github.com/thepawlow/fivem-ts-svelte-boilerplate/blob/main/frontend-doc.md Sends data to the FiveM client by emitting an event. This method is used to communicate from the NUI (browser environment) to the game server. Data is sent via HTTP POST requests. ```typescript NUIController.emit('sendData', { key: 'value' }); ``` -------------------------------- ### Register FiveM Commands with NativeWrappers Source: https://context7.com/thepawlow/fivem-ts-svelte-boilerplate/llms.txt Registers in-game commands for FiveM using `RegisterCommand` and `NativeWrappers`. This snippet demonstrates spawning vehicles and controlling NUI visibility via chat commands. It relies on dependency injection for services like LogService and NUIController. ```typescript import 'reflect-metadata'; import { container } from "./container"; import { Game, Model, Vehicle, VehicleSeat, World } from "@nativewrappers/fivem"; import { LogService } from "../shared/services/LogService"; import { NUIController } from "./controllers/NUIController"; const logger = container.get(LogService); const nuiController = container.get(NUIController); // Spawn vehicle command RegisterCommand( "adder", async (source, args) => { const playerCoords = Game.PlayerPed.Position; const vehicle = await World.createVehicle( new Model("adder"), playerCoords, 4, ); if (vehicle instanceof Vehicle) { Game.PlayerPed.setIntoVehicle(vehicle, VehicleSeat.Driver); logger.log(`Spawned Adder for ${Game.Player.Name}`); } }, false, ); // NUI control commands RegisterCommand("showNUI", async () => nuiController.Show(), false); RegisterCommand("hideNUI", async () => nuiController.Hide(), false); RegisterCommand("toggleNUI", async () => nuiController.Toggle(), false); // Register NUI callback for close button nuiController.RegisterNuiCallback("NUIControllerCloseUI", (_, cb) => { nuiController.Hide(); logger.log("NUI was closed by user."); cb({ success: true }); }); ``` -------------------------------- ### NUI Event Controller (TypeScript) Source: https://context7.com/thepawlow/fivem-ts-svelte-boilerplate/llms.txt Manages communication between the Svelte frontend and the FiveM client. Supports event registration, one-time listeners, and browser debugging. It uses a Map to store listeners for different actions and fetch for emitting events. ```typescript type NUIListener = (data: T) => void; export class NUIController { private static initialized = false; private static listeners = new Map[]>(); public static get isEnvBrowser() { return !(window as any).invokeNative; } // Register event listener with optional debug data for browser testing static on(action: string, listener: NUIListener, debugEvents?: { data: T; delay?: number }) { const listeners = this.listeners.get(action) || []; listeners.push(listener); this.listeners.set(action, listeners); // In browser environment, trigger debug events for testing if (this.isEnvBrowser && debugEvents) { setTimeout(() => listener(debugEvents.data), debugEvents.delay || 0); } } // Unregister event listener static off(action: string, listener: NUIListener) { const listeners = this.listeners.get(action) || []; const index = listeners.indexOf(listener); if (index !== -1) listeners.splice(index, 1); } // Register one-time event listener static once(action: string, listener: NUIListener) { const onceListener: NUIListener = (data) => { this.off(action, onceListener); return listener(data); }; this.on(action, onceListener); } // Emit event to FiveM client static emit(action: string, data?: T) { const resourceName = (window as any).GetParentResourceName?.() ?? "nui"; return fetch(`https://${resourceName}/${action}`, { method: 'POST', headers: { 'Content-Type': 'application/json; charset=UTF-8' }, body: JSON.stringify(data) }); } } ``` -------------------------------- ### Manage NUI Visibility and Communication Source: https://context7.com/thepawlow/fivem-ts-svelte-boilerplate/llms.txt Manages the visibility state and communication for the NUI (Native User Interface) in a FiveM client. It provides methods to show, hide, and toggle the NUI, handle focus, and send messages to the web UI. Dependencies include LogService. ```typescript import { inject, injectable } from "inversify"; import { LogService } from "../../shared/services/LogService"; @injectable() export class NUIController { private _isVisible: boolean = false; constructor( @inject(LogService) private logService: LogService ) { } public get IsVisible(): boolean { return this._isVisible; } private setNuiState(state: boolean): void { SetNuiFocus(state, state); this.Send("showUI", state); this._isVisible = state; this.logService.log(`NUI Visibility changed: ${state}`); } public Show(): void { if (!this._isVisible) this.setNuiState(true); } public Hide(): void { if (this._isVisible) this.setNuiState(false); } public Toggle(): void { this.setNuiState(!this._isVisible); } public Send(event: string, data: any): void { this.logService.log(`Sending NUI Message: ${event}`); SendNUIMessage({ action: event, data }); } public RegisterNuiCallback(key: string, callback: (data: any, cb: (arg: any) => void) => void): void { this.logService.log(`Registered Callback ${key}`); RegisterNuiCallbackType(key); on(`__cfx_nui:${key}`, callback); } } ``` -------------------------------- ### Register Event Listener with NUIController Source: https://github.com/thepawlow/fivem-ts-svelte-boilerplate/blob/main/frontend-doc.md Registers a callback function to listen for a specific NUI event. The callback receives data emitted with the event. This is a fundamental method for receiving messages from the FiveM client. ```typescript NUIController.on('myEvent', (data) => { console.log('Received data:', data); }); ``` -------------------------------- ### Register One-Time Event Listener with NUIController Source: https://github.com/thepawlow/fivem-ts-svelte-boilerplate/blob/main/frontend-doc.md Registers a callback function that will be executed only once for a specific NUI event. After the event is triggered and the listener is called, it automatically unregisters itself. ```typescript NUIController.once('singleEvent', (data) => { console.log('This will only trigger once:', data); }); ``` -------------------------------- ### Shared Logging Service with TypeScript Source: https://context7.com/thepawlow/fivem-ts-svelte-boilerplate/llms.txt Implements a shared LogService using TypeScript and Inversify for dependency injection. This service provides a consistent way to log messages across server and client sides, prepending a source identifier to each log entry. It requires the 'inversify' package. ```typescript import { injectable } from "inversify"; @injectable() export class LogService { log(message: string) { console.log(`[Server Log]: ${message}`); } } // Usage in any controller import { inject, injectable } from "inversify"; import { LogService } from "../shared/services/LogService"; @injectable() export class MyController { constructor( @inject(LogService) private logService: LogService ) {} doSomething() { this.logService.log("Operation completed successfully"); // Output: [Server Log]: Operation completed successfully } } ``` -------------------------------- ### Unregister Event Listener with NUIController Source: https://github.com/thepawlow/fivem-ts-svelte-boilerplate/blob/main/frontend-doc.md Removes a previously registered event listener. This is useful for cleaning up event handlers when they are no longer needed, preventing memory leaks and unintended behavior. ```typescript const myListener = (data) => console.log('Received:', data); NUIController.on('testEvent', myListener); NUIController.off('testEvent', myListener); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.