Skip to content

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 FishingLog

Using 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

ModelSchema
Locationshared/models/Inline in service
PurposeNamed, reusable data structureOne-off validation
DocumentedYes — shows up in API referenceNo

Use a Model when the shape of the data is important enough to name and document. Use inline schemas for quick input validation.

See Also

Released under the MIT License.