### Install ox_core with npm Source: https://github.com/overextended/ox_core/blob/main/_autodocs/getting-started.md Install the ox_core package using npm. This is a prerequisite for setting up the framework. ```bash npm install @overextended/ox_core ``` -------------------------------- ### Get Vehicle Example Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-vehicle.md Demonstrates how to retrieve a vehicle using the GetVehicle function, showing examples for both entity ID and VIN. ```typescript import { GetVehicle } from '@overextended/ox_core/server'; // Get by entity ID const vehicle = GetVehicle(entityId); // Get by VIN const vehicle = GetVehicle('1OX12A1000000000'); ``` -------------------------------- ### High-Performance Server Configuration Source: https://github.com/overextended/ox_core/blob/main/_autodocs/configuration.md Example console variables for a high-performance server setup with ox_core, minimizing debug features. ```lua setr ox:characterSlots 1 setr ox:debug 0 setr sv_lan 0 ``` -------------------------------- ### Roleplay Server Configuration Source: https://github.com/overextended/ox_core/blob/main/_autodocs/configuration.md Example console variables for a roleplay server setup with ox_core, including multiple jobs and custom vehicle storage. ```lua setr ox:characterSlots 3 setr ox:plateFormat "XX##****" setr ox:defaultVehicleStore "garage" setr ox:createDefaultAccount 1 ``` -------------------------------- ### Development Server Configuration Source: https://github.com/overextended/ox_core/blob/main/_autodocs/configuration.md Example console variables for setting up a development server with ox_core. ```lua setr ox:debug 1 setr ox:characterSlots 5 setr ox:createDefaultAccount 1 setr ox:plateFormat "DEV....." ``` -------------------------------- ### Production Server Configuration Source: https://github.com/overextended/ox_core/blob/main/_autodocs/configuration.md Example console variables for configuring a production server with ox_core. ```lua setr ox:characterSlots 1 setr ox:createDefaultAccount 1 setr ox:plateFormat "....." setr sv_lan 0 ``` -------------------------------- ### Configure ox_core in fxmanifest.lua Source: https://github.com/overextended/ox_core/blob/main/_autodocs/configuration.md Example fxmanifest.lua for setting up ox_core, including shared_scripts, server_scripts, and dependencies. ```lua fx_version 'cerulean' game 'gta5' author 'Your Name' description 'Your Script' version '1.0.0' shared_scripts { '@ox_core/imports.lua' } server_scripts { '@ox_core/schema.sql', 'server.lua' } dependencies { 'ox_core', 'ox_lib' } ``` -------------------------------- ### Example API Usage Format Source: https://github.com/overextended/ox_core/blob/main/_autodocs/README.md This is the standard format used for documenting functions within the API reference files. It includes function signatures, parameter details, return types, and a realistic usage example. ```markdown ### `FunctionName(param: Type): ReturnType` Description of what the function does. **Parameters** | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | param | Type | Yes | — | What it does | **Returns** Type and description of return value. **Example** ```typescript // Real usage example const result = FunctionName(param); ``` ``` -------------------------------- ### Example Custom Locale JSON Source: https://github.com/overextended/ox_core/blob/main/_autodocs/configuration.md An example JSON file for defining custom locales in ox_core, showing ban-related messages. ```json { "ban_notice": "You have been banned.\nBan date: %s\nReason: %s\n%s", "ban_expires_in": "Ban expires in %d hours, %d minutes, %d seconds", "ban_indefinite": "This ban is permanent" } ``` -------------------------------- ### Set MySQL Environment Variables Source: https://github.com/overextended/ox_core/blob/main/_autodocs/configuration.md Example of setting MariaDB environment variables via server.cfg for ox_core database connection. ```lua set mysql_connection_string "mysql://user:pass@localhost:3306/fivem" ``` -------------------------------- ### Create Faction Groups Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-groups.md Example of creating two distinct faction groups with unique names, labels, types, and colors. ```typescript await CreateGroup({ name: 'vagos', label: 'Vagos Gang', type: 'faction', colour: 0xFFFF00, hasAccount: true, grades: [ { label: 'Prospect' }, { label: 'Member' }, { label: 'Enforcer' }, { label: 'Boss' }, ], }); await CreateGroup({ name: 'families', label: 'Families Gang', type: 'faction', colour: 0x00FF00, hasAccount: true, grades: [ { label: 'Associate' }, { label: 'Soldier' }, { label: 'Underboss' }, { label: 'Boss' }, ], }); // Only one faction per character const gangs = GetGroupsByType('faction'); ``` -------------------------------- ### GetTopVehicleStats Example Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-common.md Shows how to retrieve top performance stats for all vehicle categories or a specific category like 'land'. ```typescript import { GetTopVehicleStats } from '@overextended/ox_core'; // Get all categories const topStats = GetTopVehicleStats(); console.log('Fastest land vehicle:', topStats.land.speed); console.log('Most agile plane:', topStats.air.handling); // Get single category const landStats = GetTopVehicleStats('land'); console.log(`Top land speed: ${landStats.speed}`); ``` -------------------------------- ### get Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Retrieves a value from the player's metadata. ```APIDOC ## get(key: K | PlayerMetadata): any ### Description Retrieves a value from the player's metadata. ### Parameters #### Path Parameters * **key** (string) - Required - Metadata key ### Returns The value, or undefined if not found. ### Request Example ```typescript const job = player.get('job'); ``` ``` -------------------------------- ### GetVehicleData Example Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-common.md Demonstrates fetching all vehicles, a single vehicle by model name, and multiple vehicles using their model names. ```typescript import { GetVehicleData } from '@overextended/ox_core'; // Get all vehicles const allVehicles = GetVehicleData(); // Get single vehicle const adder = GetVehicleData('adder'); console.log(adder.name, adder.make, adder.price); // Get multiple vehicles const vehicles = GetVehicleData(['adder', 't20', 'vagrant']); for (const [model, data] of Object.entries(vehicles)) { console.log(`${model}: ${data.name}`); } ``` -------------------------------- ### Create Job Group with Account Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-groups.md Example of creating a job-type group with associated account roles for different grades. ```typescript await CreateGroup({ name: 'mechanic', label: 'Mechanic Shop', type: 'job', hasAccount: true, grades: [ { label: 'Trainee', accountRole: 'viewer' }, { label: 'Mechanic', accountRole: 'contributor' }, { label: 'Master', accountRole: 'manager' }, { label: 'Boss', accountRole: 'owner' }, ], }); // Set up permissions SetGroupPermission('mechanic', 1, 'work', 'allow'); SetGroupPermission('mechanic', 2, 'tune', 'allow'); SetGroupPermission('mechanic', 3, 'manage', 'allow'); ``` -------------------------------- ### Calling Server Exports from Another Resource Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-common.md Example of how an external resource can call server-side exports provided by ox_core to get vehicle data and group permissions. ```typescript // In another resource const vehicleData = exports.ox_core.GetVehicleData('adder'); const permissions = exports.ox_core.GetGroupPermissions('police'); ``` -------------------------------- ### Setup Job Permissions Structure Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-groups.md Asynchronously sets permissions for a group based on a provided object mapping grades to permissions. ```typescript async function SetupJobPermissions(groupName, permissions) { for (const [grade, perms] of Object.entries(permissions)) { for (const [permission, allowed] of Object.entries(perms)) { SetGroupPermission( groupName, parseInt(grade), permission, allowed ? 'allow' : 'deny' ); } } } // Usage await SetupJobPermissions('police', { 1: { patrol: true, radio: true }, 2: { patrol: true, radio: true, arrest: true }, 3: { patrol: true, radio: true, arrest: true, manage: true }, 4: { patrol: true, radio: true, arrest: true, manage: true, admin: true }, }); ``` -------------------------------- ### OxPlayer Registry Example Source: https://github.com/overextended/ox_core/blob/main/_autodocs/module-map.md Demonstrates the static registry pattern used by OxPlayer for tracking instances and enabling fast lookups by various identifiers. ```typescript class OxPlayer extends ClassInterface { protected static members: Dict = {}; protected static keys: Dict> = { userId: {}, charId: {} }; static get(id) { return this.members[id]; } static add(id, instance) { this.members[id] = instance; } } ``` -------------------------------- ### Coordinate Types Example Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-vehicle.md Demonstrates the different formats accepted for coordinate parameters, including arrays, objects, and Lua Vector3 objects. ```typescript type Vec3 = | number[] // [x, y, z] | { x: number; y: number; z: number } // Object with x, y, z | { buffer: any }; // Vector3Lua object // Examples: vehicle.respawn([100, 200, 30]); vehicle.respawn({ x: 100, y: 200, z: 30 }); vehicle.respawn(new Vector3(100, 200, 30)); ``` -------------------------------- ### OxGroupPermissions Interface and Example Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-common.md Defines the structure for group permissions, mapping grade numbers to specific permission strings and their boolean values. An example demonstrates how to populate this structure. ```typescript interface OxGroupPermissions { [grade: number]: { [permission: string]: boolean } } // Example: { 1: { patrol: true, radio: true }, 2: { patrol: true, radio: true, arrest: true, search: true }, 3: { patrol: true, radio: true, arrest: true, search: true, manage: true } } ``` -------------------------------- ### Create and Manage Vehicles Source: https://github.com/overextended/ox_core/blob/main/_autodocs/getting-started.md Create, customize, and save vehicle data. This example demonstrates spawning a vehicle, setting its plate and properties, and saving it to the database. ```typescript const vehicle = await CreateVehicle( { model: 'adder', owner: charId }, [100, 200, 30], 0 ); vehicle.setPlate('CUSTOM01'); vehicle.setProperties({ modEngineHealth: 1000 }); await vehicle.save(); ``` -------------------------------- ### Setting Up a New Job Group Source: https://github.com/overextended/ox_core/blob/main/_autodocs/getting-started.md Create a new job group, define its grades, and set specific permissions for each grade using server-side functions. This example sets up a 'mechanic' job. ```typescript import { CreateGroup, SetGroupPermission } from '@overextended/ox_core/server'; // Create the job await CreateGroup({ name: 'mechanic', label: 'Mechanic Shop', type: 'job', hasAccount: true, grades: [ { label: 'Trainee' }, { label: 'Mechanic' }, { label: 'Master' }, { label: 'Boss' }, ], }); // Set up permissions SetGroupPermission('mechanic', 1, 'work', 'allow'); SetGroupPermission('mechanic', 2, 'tune', 'allow'); SetGroupPermission('mechanic', 3, 'manage', 'allow'); ``` -------------------------------- ### Import and Use Client Player Functions Source: https://github.com/overextended/ox_core/blob/main/_autodocs/getting-started.md Import the client-side 'GetPlayer' function and use player object methods like 'get', 'getStatus', and 'getGroup'. ```typescript import { GetPlayer } from '@overextended/ox_core/client'; const player = GetPlayer(); player.get('name'); player.getStatus('hunger'); player.getGroup('police'); ``` -------------------------------- ### Lazy Loading Metadata Example Source: https://github.com/overextended/ox_core/blob/main/_autodocs/module-map.md Illustrates the lazy loading pattern for caching metadata on first access, fetching data from the player API only when needed. ```typescript get(key: string) { if (!(key in this)) { this[key] = exports.ox_core.CallPlayer('get', key) ?? null; } return this[key]; } ``` -------------------------------- ### Get Player Metadata Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Retrieves a value from the player's metadata. Returns undefined if the key is not found. ```typescript const job = player.get('job'); ``` -------------------------------- ### get Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-vehicle.md Retrieves metadata previously stored on the vehicle using its key. Returns the stored value or undefined if the key does not exist. ```APIDOC ## get ### Description Retrieves metadata from the vehicle. ### Method `get(key: string): any` ### Parameters #### Parameters - **key** (string) - Yes - Metadata key ### Returns The stored value or undefined. ### Example ```typescript const data = vehicle.get('customData'); ``` ``` -------------------------------- ### Get Player License Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Retrieves license data for a specific license type. Returns the CharacterLicense object or undefined if the license is not found. ```typescript const driverLicense = player.getLicense('driver'); ``` -------------------------------- ### Get Local Player Instance (Client-Side) Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-common.md Retrieves the singleton instance of the local player on the client. Use this to access player-specific data like their name. ```typescript import { GetPlayer } from '@overextended/ox_core/client'; const player = GetPlayer(); console.log(`Playing as: ${player.get('name')}`); ``` -------------------------------- ### Get Player's Default Account Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-account.md Retrieves the default account associated with a given character ID. This is often the starting point for managing a player's finances. ```typescript // Get player's default account const account = await GetCharacterAccount(charId); if (!account) { console.log('Player has no default account'); return; } // Check balance const balance = await account.get('balance'); console.log(`Balance: $${balance}`); // Add funds await account.addBalance({ amount: 500, message: 'Salary' }); // Remove funds const success = await account.removeBalance({ amount: 100 }); if (!success) { console.log('Insufficient funds'); } ``` -------------------------------- ### Set Up Role-Based Team Account Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-account.md Explains how to create a shared team account and assign roles ('manager' or 'contributor') to team members. It also shows how to check player permissions for specific actions. ```typescript async function SetupTeamAccount(ownerCharId, teamMembers) { // Create shared account const account = await CreateAccount(ownerCharId, 'Team Fund'); await account.setShared(); // Set up team member roles for (const member of teamMembers) { const role = member.isManager ? 'manager' : 'contributor'; await account.setCharacterRole(member.charId, role); } console.log('Team account configured'); return account.accountId; } // Check if player can perform action const canWithdraw = await account.playerHasPermission(playerId, 'withdraw'); const canAddUser = await account.playerHasPermission(playerId, 'addUser'); ``` -------------------------------- ### Create and Configure Groups Source: https://github.com/overextended/ox_core/blob/main/_autodocs/types.md Demonstrates creating a new group with specified properties and setting permissions. ```typescript import type { CreateGroupProperties, OxGroupPermissions } from '@overextended/ox_core'; import { CreateGroup, SetGroupPermission } from '@overextended/ox_core/server'; const groupData: CreateGroupProperties = { name: 'police', label: 'Police Department', type: 'job', colour: 0x0066FF, hasAccount: true, grades: [ { label: 'Recruit', accountRole: 'viewer' }, { label: 'Officer', accountRole: 'contributor' }, { label: 'Sergeant', accountRole: 'manager' }, { label: 'Chief', accountRole: 'owner' }, ], }; await CreateGroup(groupData); ``` -------------------------------- ### Get Active Players by Group Type Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-groups.md Retrieves the server source IDs of all players who are currently active in any group of a specified type. This provides a count of all players employed across all jobs, for example. ```typescript const allEmployed = GetGroupActivePlayersByType('job'); ``` -------------------------------- ### Runtime Configuration Variables Source: https://github.com/overextended/ox_core/blob/main/_autodocs/module-map.md Lists common runtime configuration variables defined in `common/config.ts` and `server/config.ts`. These variables can be set via `SetConvar()` in server.cfg before the resource starts. ```typescript // Runtime variables SV_LAN: boolean CHARACTER_SLOTS: number PLATE_PATTERN: string DEFAULT_VEHICLE_STORE: string DEBUG: boolean CREATE_DEFAULT_ACCOUNT: boolean ``` -------------------------------- ### Vehicle System API Source: https://github.com/overextended/ox_core/blob/main/_autodocs/README.md Documentation for vehicle management functions, including creation, spawning, persistence, customization, and ownership. Features over 15 OxVehicle methods with examples. ```APIDOC ## Vehicle System API Reference This section details the API for managing vehicles within the ox_core framework. It covers vehicle lifecycle, customization, ownership, and lookup functionalities. ### Functions Documented - **Vehicle Functions**: 10+ (e.g., CreateVehicle, SpawnVehicle, GetVehicle variants) - **OxVehicle Methods (Server)**: 15+ methods ### Key Features - Creating temporary and owned vehicles - Vehicle spawning and despawning - Customization (paint, mods, etc.) - Ownership (player or group) - Storage locations - Plate and VIN management ### Example Section Format ``` ### `FunctionName(param: Type): ReturnType` Description of what the function does. **Parameters** | Parameter | Type | Required | Default | Description | |-----------|------|----------|---------|-------------| | param | Type | Yes | — | What it does | **Returns** Type and description of return value. **Example** ```typescript // Real usage example const result = FunctionName(param); ``` ``` ``` -------------------------------- ### Configure database connection string Source: https://github.com/overextended/ox_core/blob/main/_autodocs/getting-started.md Set the database connection string in your server configuration. Replace 'user', 'password', and 'fivem' with your actual database credentials and name. ```cfg set mysql_connection_string "mysql://user:password@localhost/fivem" ``` -------------------------------- ### Get Vehicle Metadata Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-vehicle.md Retrieve metadata previously stored on a vehicle using the `get` method. Returns `undefined` if the key does not exist. ```typescript const data = vehicle.get('customData'); ``` -------------------------------- ### Get Player Account Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Gets the default account associated with the player's active character. Returns null if the character is not loaded or the account does not exist. ```typescript const account = await player.getAccount(); if (account) { const balance = await account.get('balance'); } ``` -------------------------------- ### Ensure Database Dependencies and Verify Connection String Source: https://github.com/overextended/ox_core/blob/main/_autodocs/configuration.md Make sure 'mysql-async' and 'oxmysql' are ensured, and verify that the 'mysql_connection_string' is correctly set in your server configuration. ```bash ensure mysql-async ensure oxmysql // Verify connection string set mysql_connection_string "mysql://user:password@host:port/database" ``` -------------------------------- ### Get Active Players in a Group Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-groups.md Gets the server source IDs of all players currently active within a specific group. Useful for checking real-time group membership. ```typescript const activeCops = GetGroupActivePlayers('police'); console.log(`${activeCops.length} police officers on duty`); ``` -------------------------------- ### Get Player Metadata by Key Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Retrieves a specific piece of player metadata using its key. The data is cached and automatically updated. Returns null if the key is not found. ```typescript const name = player.get('name'); // string const activeGroup = player.get('activeGroup'); // string | undefined ``` -------------------------------- ### GetGroupActivePlayers Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-groups.md Gets the server source IDs of all players currently active in a specified group. ```APIDOC ## GetGroupActivePlayers groupName ### Description Gets all player source IDs currently in a group's active status. ### Parameters #### Path Parameters - **groupName** (string) - Required - Group name ### Returns Array of player server source IDs. ### Example ```typescript const activeCops = GetGroupActivePlayers('police'); console.log(`${activeCops.length} police officers on duty`); ``` ``` -------------------------------- ### Get Player Coordinates Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Returns the player's current coordinates as an array of [x, y, z]. ```typescript const [x, y, z] = player.getCoords(); ``` -------------------------------- ### Get Player by Character ID Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Retrieves an OxPlayer instance using their active character ID. ```typescript const player = GetPlayerFromCharId(456); ``` -------------------------------- ### Configure server.cfg for ox_core Source: https://github.com/overextended/ox_core/blob/main/_autodocs/getting-started.md Configure essential server settings for ox_core by adding these lines to your server.cfg file. Ensure ox_lib is also ensured. ```cfg setr ox:characterSlots 3 setr ox:plateFormat "XX####" setr ox:defaultVehicleStore "garage" setr ox:createDefaultAccount 1 ensure ox_lib ensure ox_core ``` -------------------------------- ### Get All Player Groups Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Returns an object mapping all group names the player belongs to, with their corresponding grades. ```typescript player.getGroups(); ``` -------------------------------- ### Create and Configure Shared Account Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-account.md Initializes a new account for a player and then converts it into a shared account. Access for other characters can be granted using `setCharacterRole`. ```typescript // Create account for a player const account = await CreateAccount(charId, 'Family Account'); // Make it shared await account.setShared(); // Grant access to other characters await account.setCharacterRole(otherId, 'contributor'); await account.setCharacterRole(thirdId, 'manager'); console.log('Shared account created'); ``` -------------------------------- ### Create and Manage Characters Source: https://github.com/overextended/ox_core/blob/main/_autodocs/types.md Demonstrates how to create a new character using the NewCharacter type and player API. ```typescript import { GetPlayer } from '@overextended/ox_core/server'; import type { Character, NewCharacter } from '@overextended/ox_core'; const player = GetPlayer(source); // Create new character const newChar: NewCharacter = { firstName: 'John', lastName: 'Doe', gender: 'M', date: Date.now(), }; await player.createCharacter(newChar); ``` -------------------------------- ### Get Vehicle Properties Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-vehicle.md Fetch all customization properties of the vehicle, including engine health, paint, and modifications. ```typescript const props = vehicle.getProperties(); console.log(props.modEngineHealth); ``` -------------------------------- ### Get First Player by Filter Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Retrieves the first OxPlayer instance that matches the provided filter criteria. ```typescript const player = GetPlayerFromFilter({ firstName: 'John' }); ``` -------------------------------- ### Enable Create Default Account Source: https://github.com/overextended/ox_core/blob/main/_autodocs/configuration.md Automatically creates a default account when a new character is created. Requires ox_core resource to be running. Set this in your server.cfg. ```lua setr ox:createDefaultAccount 1 ``` -------------------------------- ### OxAccount.get Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-account.md Gets a single metadata value or multiple values from the account. This method is part of the Server OxAccount Instance. ```APIDOC ## OxAccount.get(key: T): Promise ### Description Gets a single metadata value from the account. ### Parameters #### Path Parameters - **key(s)** (string | string[]) - Yes - Single key or array of keys ### Returns Promise resolving to the value(s) or null if account doesn't exist. ### Request Example ```typescript // Get single value const balance = await account.get('balance'); // Get multiple values const data = await account.get(['balance', 'label', 'type']); console.log(data.balance, data.label); ``` ``` -------------------------------- ### Creating and Managing Vehicles Workflow Source: https://github.com/overextended/ox_core/blob/main/_autodocs/getting-started.md Handle vehicle lifecycle from creation and customization to saving and spawning from the database. Includes options for despawning vehicles. ```typescript // Create and spawn const vehicle = await CreateVehicle( { model: 'adder', owner: charId }, [100, 200, 30] ); // Customize vehicle.setPlate('MYPLATE'); vehicle.setProperties({ modEngineHealth: 1000, modBodyHealth: 1000, modPrimaryColor: 'RGB(255, 0, 0)', }); await vehicle.save(); // Later: spawn from database const spawned = await SpawnVehicle(vehicle.id, [150, 250, 40]); // Or despawn without removing from database vehicle.despawn(true); ``` -------------------------------- ### Get All Player Statuses Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Returns an object that maps all current player status names to their numerical values (0-100). ```typescript const statuses = player.getStatuses(); // { hunger: 42, thirst: 58, stress: 10 } ``` -------------------------------- ### Setting Group Permissions Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-groups.md Demonstrates how to set permissions for specific grades within a group, showing inheritance rules. ```typescript SetGroupPermission('police', 1, 'patrol', 'allow'); // All grades can patrol SetGroupPermission('police', 2, 'arrest', 'allow'); // Grade 2+ can arrest SetGroupPermission('police', 3, 'manage', 'allow'); // Grade 3+ can manage // Grade 3 has: patrol, arrest, manage // Grade 2 has: patrol, arrest // Grade 1 has: patrol ``` -------------------------------- ### Set Database Connection Pool Size Source: https://github.com/overextended/ox_core/blob/main/_autodocs/configuration.md Tune the minimum and maximum number of database connections in the pool using environment variables. ```bash set mysql_pool_min "2" set mysql_pool_max "10" ``` -------------------------------- ### getGroupByType Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Gets the player's group of a specific type, returning a tuple of [groupName, grade] or an empty array if not found. ```APIDOC ## getGroupByType(type: string): [string, number] | [] ### Description Gets the player's group of a specific type. ### Parameters #### Path Parameters * **type** (string) - Required - Group type ### Returns Tuple [groupName, grade] or empty array. ### Request Example ```typescript const [job] = player.getGroupByType('job') || []; ``` ``` -------------------------------- ### getGroup Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Gets the player's grade in a specific group or groups. The return type varies based on the filter provided. ```APIDOC ## getGroup(filter: string): number ## getGroup(filter: string[] | Record): [string, number] | [] ### Description Gets the player's grade in a specific group. ### Parameters #### Path Parameters * **filter** (string | string[] | object) - Required - Group name(s) ### Returns Grade or tuple depending on filter type. ### Request Example ```typescript const police = player.getGroup('police'); // 2 const [job, grade] = player.getGroup(['police', 'fire']) || []; ``` ``` -------------------------------- ### Add Player License Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Gives the player a specified license. Returns true if the operation was successful. ```typescript await player.addLicense('driver'); ``` -------------------------------- ### Permission Formats Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-groups.md Illustrates the structure of simple and hierarchical permissions used within groups. ```typescript // Simple permissions 'arrest' 'search' 'fine' // Hierarchical permissions 'management.hire' 'management.fire' 'management.promote' 'patrol.breathalyzer' 'patrol.weapons' ``` -------------------------------- ### Enable Server LAN Mode Source: https://github.com/overextended/ox_core/blob/main/_autodocs/configuration.md Enables FiveM's LAN mode, which also activates debug logging in ox_core. Set this in your server.cfg. ```lua set sv_lan 1 ``` -------------------------------- ### Get Player by User ID Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Retrieves an OxPlayer instance using their unique user ID, typically derived from their license. ```typescript const player = GetPlayerFromUserId(123); ``` -------------------------------- ### GetVehicles Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-vehicle.md Retrieves all loaded vehicles, optionally filtered by properties. Can be used to get all vehicles or specific subsets based on criteria. ```APIDOC ## GetVehicles ### Description Retrieves all loaded vehicles, optionally filtered by properties. ### Method `GetVehicles(filter?: Dict): OxVehicle[]` ### Parameters #### Query Parameters - **filter** (object) - Optional - Object with properties to match ### Returns Array of OxVehicle instances. ### Request Example ```typescript // Get all vehicles const all = GetVehicles(); // Get vehicles owned by charId 123 const owned = GetVehicles({ owner: 123 }); // Get group vehicles const groupVehicles = GetVehicles({ group: 'police' }); ``` ``` -------------------------------- ### Include ox_core in fxmanifest.lua Source: https://github.com/overextended/ox_core/blob/main/_autodocs/getting-started.md Declare ox_core and ox_lib as dependencies and include necessary shared and server scripts in your fxmanifest.lua file. ```lua fx_version 'cerulean' game 'gta5' shared_scripts { '@ox_core/imports.lua' } server_scripts { '@ox_core/schema.sql', 'server.lua' } dependencies { 'ox_core', 'ox_lib' } ``` -------------------------------- ### Get All Player Groups Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Returns a dictionary containing all groups the player is a member of, mapping group names to their respective grades. ```typescript const groups = player.getGroups(); // { police: 2, fire: 1 } ``` -------------------------------- ### GetPlayer() Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Retrieves the local player instance on the client. This is a singleton that manages the current character's data. ```APIDOC ## GetPlayer() ### Description Returns the local player instance on the client. This is a singleton that manages the current character's data. ### Returns An `OxPlayer` instance with the following properties: - `userId: number` - The unique user identifier - `charId?: number` - The active character ID (undefined until character is loaded) - `stateId?: string` - The state ID of the active character - `state: StateBagInterface` - Access to the player's state bag ### Example ```typescript import { GetPlayer } from '@overextended/ox_core/client'; const player = GetPlayer(); console.log(player.userId, player.charId); ``` ``` -------------------------------- ### Get Player Ped Coordinates Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Fetches the current [x, y, z] coordinates of the player's character model (ped). ```typescript const [x, y, z] = player.getCoords(); console.log(`Player at ${x}, ${y}, ${z}`); ``` -------------------------------- ### CreateVehicle Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-vehicle.md Creates a vehicle instance and optionally spawns it at specified coordinates and heading. Can be initiated with a model name or detailed creation data. ```APIDOC ## CreateVehicle ### Description Creates a vehicle instance and optionally spawns it at coordinates. ### Method `CreateVehicle(data: string | CreateVehicleData, coords?: Vec3, heading?: number): Promise` ### Parameters #### Path Parameters - **data** (string | CreateVehicleData) - Required - Model name or creation data - **coords** (Vec3) - Optional - Spawn coordinates (x, y, z) - **heading** (number) - Optional - Heading in degrees ### Returns Promise resolving to OxVehicle instance. ### Request Example ```typescript // Simple spawn const vehicle = await CreateVehicle('police', [100, 200, 30]); // With owner and properties const owned = await CreateVehicle({ model: 'adder', owner: charId, properties: { modEngineHealth: 1000, modBodyHealth: 1000, } }, [100, 200, 30], 90); // Just create instance (no spawn) const vehicle = await CreateVehicle({ model: 'police' }); ``` ``` -------------------------------- ### Interact with Account Types Source: https://github.com/overextended/ox_core/blob/main/_autodocs/types.md Illustrates fetching account details and creating an invoice using account-related types and functions. ```typescript import type { OxAccountMetadata, OxCreateInvoice } from '@overextended/ox_core/server'; import { GetAccount } from '@overextended/ox_core/server'; const account = await GetAccount(123); const metadata = await account.get(['balance', 'label']); const invoice: OxCreateInvoice = { fromAccount: account.accountId, toAccount: 456, amount: 1000, message: 'Payment', dueDate: new Date().toISOString(), }; ``` -------------------------------- ### Get Group Account Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-account.md Retrieves the default account for a specified group name. Returns null if the group does not have an associated account. ```typescript const account = await GetGroupAccount('police'); if (account) { await account.addBalance({ amount: 1000 }); } ``` -------------------------------- ### Create and Spawn a Vehicle Source: https://github.com/overextended/ox_core/blob/main/_autodocs/INDEX.md Use `CreateVehicle` to instantiate a vehicle with specified model and group, then set its plate and save it to the database. The `save()` method is asynchronous. ```typescript const vehicle = await CreateVehicle( { model: 'police', group: 'police' }, [100, 200, 30] ); vehicle.setPlate('POLICE01'); await vehicle.save(); ``` -------------------------------- ### Get Vehicle by Network ID Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-vehicle.md Retrieves a vehicle instance by its network ID. Use this when dealing with network-related vehicle data. ```typescript const vehicle = GetVehicleFromNetId(networkId); ``` -------------------------------- ### Get Account by ID Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-account.md Retrieves an account instance using its unique account ID. Ensure the account ID is valid. ```typescript import { GetAccount } from '@overextended/ox_core/server'; const account = await GetAccount(123); const balance = await account.get('balance'); ``` -------------------------------- ### Efficient Player Instance Lookups Source: https://github.com/overextended/ox_core/blob/main/_autodocs/INDEX.md Use static methods on OxPlayer for efficient lookups of player instances by source, userId, or charId. ```typescript By source: OxPlayer.get(source) By userId: OxPlayer.getFromUserId(userId) By charId: OxPlayer.getFromCharId(charId) ``` -------------------------------- ### License Interface Source: https://github.com/overextended/ox_core/blob/main/_autodocs/types.md Defines the structure for a license, including optional display names. ```typescript interface OxLicense { name?: string; label?: string; } ``` -------------------------------- ### getLicenses Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Retrieves all licenses held by the player. Returns an object mapping license names to their respective data. ```APIDOC ## getLicenses(): { [key: string]: CharacterLicense } ### Description Gets all licenses the player has. ### Returns * **{ [key: string]: CharacterLicense }** - Object mapping license names to license data. ``` -------------------------------- ### set Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Stores a value in the player's metadata. This value can optionally be replicated to the client. ```APIDOC ## set(key: K | PlayerMetadata, value: any, replicated?: boolean): void ### Description Stores a value in the player's metadata. Can optionally replicate to client. ### Parameters #### Path Parameters * **key** (string) - Required - Metadata key * **value** (any) - Required - Value to store * **replicated** (boolean) - Optional - Whether to sync to client (defaults to false) ### Request Example ```typescript player.set('job', 'police', true); // Replicate to client player.set('internalNotes', 'VIP player', false); ``` ``` -------------------------------- ### getAccount Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Gets the default account associated with the player's active character. Returns null if the character or account doesn't exist. ```APIDOC ## async getAccount(): Promise ### Description Gets the default account associated with the player's active character. ### Returns OxAccount instance or null if character not loaded or account doesn't exist. ### Request Example ```typescript const account = await player.getAccount(); if (account) { const balance = await account.get('balance'); } ``` ``` -------------------------------- ### Character Loading Data Flow Source: https://github.com/overextended/ox_core/blob/main/_autodocs/module-map.md Illustrates the sequence of events and database operations involved in loading a player's character upon connection. ```mermaid graph TD A[Client connects] B(ox:playerLoaded event fires) C(OxPlayer instance created) D(Character loaded from database) E(Metadata fetched) F(Client receives via ox:setActiveCharacter event) G(Client PlayerInterface initialized) H[Player ready to play] A --> B --> C --> D --> E --> F --> G --> H ``` -------------------------------- ### Get Player State Bag Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Returns the player's state bag for direct access. Use this to manage client-side state. ```typescript player.getState().set('myKey', 'value', true); ``` -------------------------------- ### Get Player by Source ID Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Retrieves an OxPlayer instance using their server source ID. This function requires an import from '@overextended/ox_core/server'. ```typescript import { GetPlayer } from '@overextended/ox_core/server'; const player = GetPlayer(1); if (player?.charId) { console.log(player.get('name')); } ``` -------------------------------- ### GetPlayer() Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-common.md Retrieves the local player instance on the client. This function is intended for client-side use only. ```APIDOC ## GetPlayer() ### Description Gets the local player instance (client only). ### Returns OxPlayer singleton. ### Example ```typescript import { GetPlayer } from '@overextended/ox_core/client'; const player = GetPlayer(); console.log(`Playing as: ${player.get('name')}`); ``` ``` -------------------------------- ### Get Vehicle by VIN Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-vehicle.md Retrieves a vehicle instance by its Vehicle Identification Number (VIN). Ideal for unique identification using the VIN. ```typescript const vehicle = GetVehicleFromVin('1OX12A1000000000'); ``` -------------------------------- ### Import Server Module Functions Source: https://github.com/overextended/ox_core/blob/main/_autodocs/getting-started.md Import specific server-side functions for managing players, vehicles, accounts, and groups. ```typescript import { GetPlayer, GetPlayers, GetVehicle, GetVehicles, GetAccount, GetCharacterAccount, CreateGroup, SetGroupPermission, } from '@overextended/ox_core/server'; ``` -------------------------------- ### Get Vehicle by Entity ID Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-vehicle.md Retrieves a vehicle instance by its entity handle. Useful for direct access when the entity ID is known. ```typescript const vehicle = GetVehicleFromEntity(entityId); if (vehicle?.owner) { console.log('Vehicle is owned'); } ``` -------------------------------- ### Declare ox_core and ox_lib Dependencies Source: https://github.com/overextended/ox_core/blob/main/_autodocs/configuration.md Declare ox_core and ox_lib as dependencies in your fxmanifest.lua file to ensure they are loaded correctly. ```lua dependencies { 'ox_core', 'ox_lib' } ``` -------------------------------- ### Get Vehicle by Entity ID or VIN Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-vehicle.md Retrieves a vehicle instance using its entity ID or VIN. Use this when you have one of these identifiers. ```typescript function GetVehicle(entityId: number): OxVehicle; function GetVehicle(vin: string): OxVehicle; ``` -------------------------------- ### Manage Character Accounts and Balances Source: https://github.com/overextended/ox_core/blob/main/_autodocs/getting-started.md Interact with character accounts to retrieve balances, add funds, remove funds, and transfer money between accounts. Use await for asynchronous account operations. ```typescript const account = await GetCharacterAccount(charId); const balance = await account.get('balance'); await account.addBalance({ amount: 500, message: 'Salary' }); ``` -------------------------------- ### CreateAccount Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-account.md Creates a new account. This function is intended for server-side use. ```APIDOC ## CreateAccount(owner: number | string, label: string): Promise ### Description Creates a new account. ### Parameters #### Path Parameters - **owner** (number | string) - Yes - Owner charId or group name - **label** (string) - Yes - Display name for the account ### Returns Promise resolving to newly created OxAccount. ### Request Example ```typescript const account = await CreateAccount(charId, 'Savings Account'); const account2 = await CreateAccount('police', 'Police Fund'); ``` ``` -------------------------------- ### Get Vehicle Storage Location Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-vehicle.md Retrieve the current storage location of the vehicle, such as 'impound' or 'garage'. Returns `null` if the vehicle is not currently stored. ```typescript const location = vehicle.getStored(); if (location === 'impound') { // Vehicle is impounded } ``` -------------------------------- ### Register Player Data Update Handler Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Sets up a callback to be executed when specific player metadata changes. The callback is invoked immediately if the data already exists. ```typescript const player = GetPlayer(); player.on('name', (name) => { console.log('Player name updated:', name); }); ``` -------------------------------- ### Create a Job Group Source: https://github.com/overextended/ox_core/blob/main/_autodocs/INDEX.md Use `CreateGroup` to define a new job with specific roles and permissions. Ensure the group has an account associated with it for financial operations. ```typescript await CreateGroup({ name: 'police', label: 'Police Department', type: 'job', hasAccount: true, grades: [ { label: 'Recruit', accountRole: 'viewer' }, { label: 'Officer', accountRole: 'contributor' }, { label: 'Chief', accountRole: 'owner' }, ], }); SetGroupPermission('police', 2, 'arrest', 'allow'); ``` -------------------------------- ### Get Vehicle Coordinates Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-vehicle.md Obtain the current world coordinates [x, y, z] of a vehicle. Returns `null` if the vehicle is not currently spawned in the world. ```typescript const [x, y, z] = vehicle.getCoords() || [0, 0, 0]; ``` -------------------------------- ### OxPlayer Methods Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-player.md Methods available on the OxPlayer instance for interacting with player data. ```APIDOC ## OxPlayer Methods ### on(key: string, callback: (data: unknown) => void): void #### Description Registers an event handler that triggers when specified player data is updated. The handler is called immediately if data already exists. #### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | key | string | Yes | The player metadata key to watch | | callback | function | Yes | Callback function receiving the updated value | #### Example ```typescript const player = GetPlayer(); player.on('name', (name) => { console.log('Player name updated:', name); }); ``` ### get(key: K | keyof PlayerMetadata): any #### Description Returns player data for the specified key. Data is cached and automatically kept up-to-date. Returns `null` if not found. #### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | key | string | Yes | The player metadata key | #### Returns The value associated with the key, or null. #### Example ```typescript const name = player.get('name'); // string const activeGroup = player.get('activeGroup'); // string | undefined ``` ### getCoords(): number[] #### Description Returns the current coordinates of the player's ped. #### Returns Array of [x, y, z] coordinates. #### Example ```typescript const [x, y, z] = player.getCoords(); console.log(`Player at ${x}, ${y}, ${z}`); ``` ### getGroup(filter: string | string[] | Record): number | [string, number] | [] #### Description Gets the player's current grade in a specific group or multiple groups. #### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | filter | string \| string[] \| object | Yes | Group name(s) to check | #### Returns - For string filter: the grade number, or undefined if not a member - For array/object filter: tuple of [groupName, grade] or empty array #### Example ```typescript // Check single group const policeGrade = player.getGroup('police'); // 2 // Check multiple groups const [groupName, grade] = player.getGroup(['police', 'fire']) || []; // Check with minimum grade requirement const [name, g] = player.getGroup({ police: 2, fire: 1 }) || []; ``` ### getGroupByType(type: string): [string, number] | [] #### Description Gets the player's group membership for a specific group type. #### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | type | string | Yes | The group type to search for | #### Returns Tuple of [groupName, grade] or empty array if not a member of any group of that type. #### Example ```typescript const [job, grade] = player.getGroupByType('job') || []; ``` ### getGroups(): { [key: string]: number } #### Description Returns all groups the player belongs to as a dictionary of groupName -> grade. #### Returns Object mapping group names to grades. #### Example ```typescript const groups = player.getGroups(); // { police: 2, fire: 1 } ``` ### getStatus(name: string): number #### Description Gets the current value of a player status (0-100). #### Parameters | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | name | string | Yes | Status name (e.g., 'hunger', 'thirst') | #### Returns Status value (0-100), or undefined if status doesn't exist. #### Example ```typescript const hunger = player.getStatus('hunger'); // 42 ``` ### getStatuses(): { [key: string]: number } #### Description Returns all player statuses and their current values. #### Returns Object mapping status names to values. #### Example ```typescript const statuses = player.getStatuses(); // { hunger: 42, thirst: 58, stress: 10 } ``` ``` -------------------------------- ### Get Account Metadata Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-account.md Retrieves metadata values from an account instance. Can fetch a single value by key or multiple values by an array of keys. ```typescript // Get single value const balance = await account.get('balance'); // Get multiple values const data = await account.get(['balance', 'label', 'type']); console.log(data.balance, data.label); ``` -------------------------------- ### Get Character's Default Account Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-account.md Retrieves the default account associated with a character ID. Returns null if the character or their account is not found. ```typescript const account = await GetCharacterAccount(charId); if (account) { const metadata = await account.get('label'); console.log(`Character's account: ${metadata}`); } ``` -------------------------------- ### Handle Invoice Workflow Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-account.md Illustrates the process of creating an invoice, paying it later, or deleting it if unpaid. Invoices can be created with a due date and associated with a specific actor. ```typescript // Create invoice const invoiceId = await fromAccount.createInvoice({ toAccount: recipientAccountId, amount: 1000, message: 'Service payment', dueDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toISOString(), actorId: charId, }); // Later, pay invoice const success = await PayAccountInvoice(invoiceId, payerCharId); if (success) { console.log('Invoice paid'); } else { console.log('Payment failed'); } // Or delete unpaid invoice await DeleteAccountInvoice(invoiceId); ``` -------------------------------- ### Get Group by Name Source: https://github.com/overextended/ox_core/blob/main/_autodocs/api-reference-groups.md Retrieves a group instance using its name. Use this to access group details like its label and available grades. ```typescript import { GetGroup } from '@overextended/ox_core/server'; const police = GetGroup('police'); if (police) { console.log(`Group: ${police.label}, Grades: ${Object.keys(police.grades).length}`); } ``` -------------------------------- ### ox_core Common Configuration API (TypeScript) Source: https://github.com/overextended/ox_core/blob/main/_autodocs/configuration.md Exports common configuration constants available in TypeScript. Includes server-only configurations. ```typescript export const SV_LAN: boolean; export const CHARACTER_SLOTS: number; export const PLATE_PATTERN: string; export const DEFAULT_VEHICLE_STORE: string; export const DEBUG: boolean; ``` ```typescript export const CREATE_DEFAULT_ACCOUNT: boolean; ```