Models
Models are shared data structures — tables with a defined schema used for validation and documentation.
What Is a Model?
A model:
- Lives in
shared/models/ - Has a schema (field names, types, defaults)
- Is validated when data enters the system
- Is used as documentation for what data looks like
Defining a Model
lua
-- shared/models/FishingLog.lua
local Validator = require('shiva-fw.validator')
local FishingLog = {}
FishingLog.schema = Validator.schema({
player_id = { type = 'number', required = true },
fish = { type = 'string', required = true, maxLength = 64 },
caught_at = { type = 'string', optional = true },
})
--- Create and validate a FishingLog
---@param data table
---@return table, table|nil (data, errors)
function FishingLog.create(data)
return FishingLog.schema:validate(data)
end
return FishingLogUsing a Model
lua
local FishingLog = require('shared.models.FishingLog')
local log, errors = FishingLog.create({
player_id = source,
fish = 'fish_bass',
})
if errors then
Log.warn('Invalid fishing log', { errors = errors })
return
end
DB:execute('INSERT INTO fishing_logs ...', log)Model vs Schema
| Model | Schema | |
|---|---|---|
| Location | shared/models/ | Inline in service |
| Purpose | Named, reusable data structure | One-off validation |
| Documented | Yes — shows up in API reference | No |
Use a Model when the shape of the data is important enough to name and document. Use inline schemas for quick input validation.