Novel
Get NovelGuidesAPI Reference
Latest - 2025.1.0
Latest - 2025.1.0
  • Welcome to Novel
  • Start
  • Philosophy
  • Tech Stack
  • Releases
  • Versions
  • Changelog
  • License
  • Privacy
  • Warranty
  • Security Policy
  • Errors
    • Cannot start Novel
    • Unauthorized
    • Invalid Session
    • Validation Failed
  • Novel Server
    • Getting Started
    • Project Structure
    • With Novel Web
    • Configuration
    • Novel CLI
      • novel dev
      • novel start
      • novel new
    • Novel API
      • API Reference
    • Database
      • Caching
    • Migrations
    • Models
    • Routing
      • Route Directives
      • Middleware
      • Request Helpers
      • Schema
    • Sessions
    • Authentication
      • Passwords
      • Magic Links
      • Two-Factor Authentication
      • Forget Password
      • Email Verification
      • OAuth2 Support
    • Authorization
    • Users
    • Organizations
    • Subscriptions
    • Pricing
    • Validation
    • Mail
    • Notifications
    • API Keys
    • Events
    • Errors
    • Feature Flags
    • Uploading Files
    • Testing
    • Scheduled Cron Jobs
    • Background Jobs
    • Sockets
    • Logging
    • Telemetry
    • Deployment
  • Novel Web
    • Getting Started
    • Configuration
    • Project Structure
    • Routing
    • Layout and Styles
    • Authentication
    • Authorization
    • Requests
    • Request Files
    • Validation
    • Components
      • Button
      • Alerts
      • Copybox
      • Inline Notify
      • Input
      • Select
      • Toast
      • Toggle
      • Upload
      • Stripe Card
    • Hooks
      • useSession
      • useMobile
      • getSession
      • useFeature
      • useAuthorized
      • useNotification
      • useSocket
    • Localstorage
    • Errors
    • Internationalization (i18n)
    • Constants
    • Feature Flags
    • Testing
    • Telemetry
    • Deployment
    • Devtools (Alpha)
Powered by GitBook
On this page
  • Base Models
  • Model Files
  • Conventions
  • Extending Models
  • Model Helpers
  • pick(paths)
  • omit(paths)
  • at(paths)
  • entries()
  • keys()
  • Validations
  • Using Zod
  • Referencing a Model
  • Changelog

Was this helpful?

  1. Novel Server

Models

Last updated 5 months ago

Was this helpful?

Attention!

Do not update or delete models in the /packages/novel/models directory. These files are covered by warranty. Updating them may cause unforeseen problems.

Make sure you have a quick look on how Models work with Objection.js below

When Novel development starts, model files are generated based on the migration files present in your app directory.

You can start with these tutorials

During development, whenever migration changes. These are rebuilt and linted.

Make sure you commit and push these files to your repository.

Production does not generate new model files, it merely loads what's in the directories already.

Base Models

There are tables and models that come out of the box with Novel API. Below is a representation of the whole default schema.

Here are the most important models you should be familiar with

Accounts

These are models related to working with accounts and entities that require them. These are extendable by creating your own models in your app directory.

The following are features that require this model.

  1. Verifications

  2. Identities

  3. Events

  4. Notification Inbox

  5. API Keys

Organizations

These are models related to working with organizations. These are extendable by creating your own models in your app directory.

The following are features that require this model.

  1. Events

  2. Account Memberships

  3. Subscriptions

Most models have a reference to this model.

Subscriptions

These are models related to working with subscriptions. These are extendable by creating your own models in your app directory.

The following are features that require this model.

  1. Charges

  2. Usage Reporting

Remember that Novel uses Multi-Tenancy by default.

Check Organizations for more information.

Model Files

Models that are generated by Novel come with a couple of files that serve specific purposes.

These files live in your /app/models directory as well as packages/novel/models.

Filename
Description
Editable

index.ts

File that you can build your specific extensions from.

This is not overwritten during startup.

✅

base.ts

Generated based on your migration file.

Contains typescript definitions and Objection specific properties like relationships and id and table identifiers. This is overwritten every time the server starts.

schema.json

Generated based on your migration file and represents your migration file as JSON schema.

Can directly be inferred via typescript. This is overwritten every time the server starts.

zod.ts

Generated based on your migration file and represents your migration file as a Zod definition.

Can directly be inferred via typescript. This is overwritten every time the server starts.

Conventions

From the model files discussed above, a couple of conventions are applied so it works well with Novel.

  1. Each model class includes a class property of their columns and relationships.

  2. Table names are defined as plural.

  3. IDs can be both a single key or a composite one.

  4. Zod definitions are exposed in the model itself access via the .zgetter.

  5. JSON Schema validation is built in during insert and update.

  6. Each model exposes it's relationship via Objection's .relationMappingsgetter.

  7. Types are inferred from both the model's properties and zod inferred definition.

Extending Models

You can extend an existing model by using ESM/Typescript's extends feature.

This will let you inherit all the base model's properties and methods and apply your own from a different file.

You can start by extending like below

app/models/accounts/index.ts
import AccountModel from 'novel/models/accounts';

export default class Account extends AccountModel {
	async someMethod() {
		// something specific to your app
		// follow 
	}
}

And you can use this new model in your app like below

app/services/some-feature.ts
import Account from 'app/models/accounts';

await Account.someMethod();

Attention!

Do not update or delete models in the /packages/novel/models directory. These files are covered by warranty. Updating them may cause unforeseen problems.

Model Helpers

Novel Models have access to the following helpers provided by Objection as well as useful lodash ones below.

Take a look at Objection's Model implementation for the helpers available by default.

pick(paths)

const data = await SomeModel.select();

// => [ { id: 1, name: 'john' } ]
const picked = data.map(row => row.pick('id'));

console.log(picked);
// => [ { id: 1 } ]

omit(paths)

const data = await SomeModel.select();

// => [ { id: 1, name: 'john' } ]
const omitted = data.map(row => row.omit('id'));

console.log(omitted);
// => [ { name: 'john' } ]

at(paths)

const data = await SomeModel.select();

// => [ { id: 1, name: 'john', settings: { utc: true } } ]
const at = data.map(row => row.at('settings.utc'));

console.log(at);
// => [ true ]

entries()

const data = await SomeModel.select();

// => [ { id: 1, name: 'john' } ]
const entries = data.map(row => row.entries());

console.log(entries);
// => [ ['id', 1], ['name', 'john'] ]

keys()

const data = await SomeModel.select();

// => [ { id: 1, name: 'john' } ]
const keys = data.map(row => row.keys());

console.log(keys);
// => [ ['id', 'name'] ]

Validations

Objection has built-in validation via JSON schema. It is applied automatically using Objection's jsonSchema getter.

In-depth explanation on how validation is performed is available below.

During generation, a JSON schema file is generated along with the base model. This schema is also fed into fastify's AJV schema registry.

Using Zod

Zod is available for the model through the .zgetter. You can use it like below

const zodModel = SomeModel.z;

// validate
zodModel.safeParse({ someInput: true });

// get the types via infer
type zodModelType = z.infer<typeof zodModel>

Types are also available via the model's directory. eg, novel/models/accounts/zod.

Referencing a Model

You are able to reference a schema in your routes by using this shorthand when defining your route schema in Fastify

{
    ...
    "$ref": "https://novel.dev/entities/accounts#"
}

Changelog

  • 2024-12-20 - Initial Documentation

Provided by lodash via . Creates an object composed of the picked object properties.

Provided by lodash via . The opposite of ; this method creates an object composed of the own and inherited enumerable property paths of object that are not omitted.

This method is considerably slower than .

Provided by lodash via . Creates an array of values corresponding to paths of object.

Provided by lodash via . Creates an array of own enumerable string keyed-value pairs for object which can be consumed by . If object is a map or set, its entries are returned.

Provided by lodash via . Creates an array of the own enumerable property names of object. Note: Non-object values are coerced to objects. See the for more details.

.pick()
.omit()
_.pick
_.pick
.at()
.toPairs()
_.fromPairs
.keys()
ES spec
Creating a Table | Novel
Models | Objection.js
Logo
Creating a Custom Model | Novel
Logo
Validation | Objection.js
Models | Objection.js