Database
Define database tables, apply modifiers for hashing and encryption, and perform CRUD operations with data models in AntelopeJS.
Prerequisites
Install the @antelopejs/interface-database-decorators package in your module. Every import on this page comes from that package.
The task API flow shows where a database provider sits behind a controller. The CRUD example on this page runs directly from a module, so it needs no HTTP server.
The package supplies table metadata and models. Before you run these examples, configure a provider of @antelopejs/interface-database, such as @antelopejs/mongodb, and a reachable database. Use a disposable database while you learn, because schema registration and the CRUD example write data.
From a table to a stored record
Follow these steps in order for a first stored record:
- Define a table, with a schema ID such as
main. - Import that table before registering the schema in
construct(). - Create a model and resolve it with
GetModelafter schema registration. - Insert and retrieve a record to verify the provider connection.
The indexes, relations, and modifiers further down extend that working path. A relation describes a link. It does not enforce a foreign key or an access policy.
Defining tables
A table is a class that extends the Table base class. The @RegisterTable decorator registers the class under a table name and a schema. Each property that has a @Field decorator is a column.
import {
Table,
RegisterTable,
Field,
Index,
} from "@antelopejs/interface-database-decorators";
@RegisterTable("users", "main")
class User extends Table {
@Index()
@Field("string")
declare email: string;
@Field("string")
declare name: string;
@Field("number")
declare age: number;
}
export { User };
The first argument to @RegisterTable is the table name and the second is the schema name. The @Field decorator declares the column type of a property. The type is a primitive token ("string", "number", "boolean", or "date"), an array such as ["string"], a nested record, or an io-ts codec. The table definition sent to the database adapter leaves out every property without @Field. The @Index decorator marks a property as indexed for faster lookups.
Table is a base class, not a decorator. Extend it with class MyTable extends Table.
Registering a database schema
Import the table, then await RegisterSchema("main") in construct(). RegisterSchema builds the schema from the tables registered under that ID and creates it through the database provider. The ID must match the second argument of @RegisterTable. If no table is registered under the ID, RegisterSchema throws No tables registered for schema 'main'.
import { RegisterSchema } from "@antelopejs/interface-database-decorators";
import "./db/tables/user";
export async function construct(): Promise<void> {
await RegisterSchema("main");
}
Data models
BasicDataModel(User) returns a model class with CRUD operations. Extend it when you need queries of your own. After schema registration, call GetModel to get its initialized instance. Do not create the model with new.
import {
BasicDataModel,
GetModel,
} from "@antelopejs/interface-database-decorators";
import { User } from "../tables/user";
class UserModel extends BasicDataModel(User) {
async getUserByEmail(email: string) {
const users = await this.getBy("email", email);
return users.length > 0 ? users[0] : null;
}
}
export function getUserModel() {
return GetModel(UserModel);
}
export { UserModel };
Insert, read, update, and delete a record
Add this import and start() callback to src/index.ts, and keep construct() from the previous step. The record matches the first User table, with name, email, and age. Run it against a disposable database, because this callback writes and deletes a record each time the module starts.
import { getUserModel } from "./db/models/user-model";
export async function start(): Promise<void> {
const model = getUserModel();
const [id] = await model.insert({
name: "Alice",
email: "[email protected]",
age: 30,
});
const created = await model.get(id);
console.log("Created:", created?.name); // Alice
await model.update(id, { name: "Alice Updated" });
const updated = await model.get(id);
console.log("Updated:", updated?.name); // Alice Updated
await model.delete(id);
console.log("Deleted:", !(await model.get(id))); // true
}
Run ajs project dev. Expect Created: Alice, Updated: Alice Updated, and Deleted: true. If schema registration fails, check the provider and database connection first. If the table is missing, check the import and schema ID. Stop the process before continuing.
Model method reference
| Instance method | Result |
|---|---|
get(id) | One table instance, or undefined when no record has the ID |
getBy(index, ...keys) | The records whose index matches the keys |
getAll() | All records |
insert(data) | Takes one record or an array. Returns an array of inserted primary keys, not the inserted records |
update(id, data) | Updates a record by primary key and returns a count |
delete(id) | Removes a record by primary key and returns a count |
The model class also has static conversion methods. fromPlainData() creates a table instance from plain data. fromDatabase() creates one from storage data. toDatabase() converts an instance back to storage data. These conversions do not read or write the database.
Extend the working example
Each of the remaining sections is a separate variation. Do not paste them one after another. The hashing and encryption examples replace the User table, so they change its required fields. Keep the basic table above until your first CRUD check works.
Indexing
The @Index decorator marks a property for database indexing. An index speeds up queries that filter or sort by the indexed column. To group several columns into a composite index, give them the same group name. Set unique: true to reject a second row with the same key, and crossInstance: true to keep the index fast for queries across instances.
import {
Table,
RegisterTable,
Field,
Index,
} from "@antelopejs/interface-database-decorators";
@RegisterTable("products", "main")
class Product extends Table {
@Index()
@Field("string")
declare sku: string;
@Index({ group: "category_brand" })
@Field("string")
declare category: string;
@Index({ group: "category_brand" })
@Field("string")
declare brand: string;
@Field("string")
declare name: string;
@Field("number")
declare price: number;
}
export { Product };
Properties with the same group value form one composite index. Queries that filter by both category and brand use it.
Relations
The @Relation decorator declares a link from a field to another table. It is metadata only. Database implementations do not enforce it with foreign key constraints. Introspection tools read it to show the links between tables.
import {
Table,
RegisterTable,
Field,
Index,
Relation,
} from "@antelopejs/interface-database-decorators";
import { User } from "./user";
@RegisterTable("orders", "main")
class Order extends Table {
@Index()
@Field("string")
@Relation({ to: () => User })
declare userId: string;
@Field("number")
declare total: number;
}
export { Order };
The to option is a function that returns the target table class. Because the call is deferred, a table can refer to a class declared later. Use toField to point at a field other than the target's primary key. Use many: true when the field holds an array of target keys.
Table modifiers
Modifiers add behavior to table properties. Apply them through Table.with(), which returns a base class with those modifiers enabled. You can pass several modifiers at once.
Hashing
The HashModifier enables the @Hashed decorator for properties that store hashed values, such as passwords. A hash is one-way, so nobody can recover the original value from it.
import {
Table,
RegisterTable,
Field,
Index,
Hashed,
} from "@antelopejs/interface-database-decorators";
import { HashModifier } from "@antelopejs/interface-database-decorators";
@RegisterTable("users", "main")
class User extends Table.with(HashModifier) {
@Index()
@Field("string")
declare email: string;
@Hashed()
@Field("string")
declare password: string;
@Field("string")
declare name: string;
}
export { User };
The modifier hashes the password field when you set it, so the database never receives the plaintext. It uses sha256 with a generated random salt. Pass @Hashed({ algorithm }) to choose another algorithm. To check a candidate password, call the testHash(field, value) method that the modifier adds to table instances.
Encryption
The EncryptionModifier enables the @Encrypted decorator for properties that must be stored encrypted. Unlike a hash, an encrypted value is decrypted when you read it back.
import {
Table,
RegisterTable,
Field,
Index,
Encrypted,
} from "@antelopejs/interface-database-decorators";
import { EncryptionModifier } from "@antelopejs/interface-database-decorators";
const secretKey = process.env.DATABASE_ENCRYPTION_KEY;
if (!secretKey || Buffer.byteLength(secretKey, "utf8") !== 32) {
throw new Error("DATABASE_ENCRYPTION_KEY must contain exactly 32 UTF-8 bytes");
}
@RegisterTable("users", "main")
class User extends Table.with(EncryptionModifier) {
@Index()
@Field("string")
declare email: string;
@Encrypted({ secretKey })
@Field("string")
declare socialSecurityNumber: string;
@Field("string")
declare name: string;
}
export { User };
The modifier encrypts the field on write and decrypts it on read. The secretKey option is required and holds the encryption key. You can also set algorithm, which defaults to aes-256-gcm, and ivSize, which defaults to 16.
Supply a randomly generated key through your secret-management system before loading the table. For the default algorithm, this API passes the string to Node.js unchanged. The string must contain 32 UTF-8 bytes, not a 64-character hex encoding of 32 bytes. Keep the same key to read existing records, and plan rotation and recovery before storing data. Do not commit keys or log decrypted fields.
Combining modifiers
To apply several modifiers, pass them all to Table.with(). Passing both modifiers enables @Hashed and @Encrypted on the same table class.
Use class User extends Table.with(HashModifier, EncryptionModifier) and keep the @Hashed() and @Encrypted({ secretKey }) fields you need from the preceding examples. Nobody can recover a hashed value. Encrypted fields are decrypted on read, so do not return them from an API unless the caller needs them.
Fixtures
The @Fixture decorator provides seed data for development and testing. It takes a generator function that receives the table class and returns a record, an array of records, or a promise of either.
import {
Table,
RegisterTable,
Field,
Fixture,
} from "@antelopejs/interface-database-decorators";
@Fixture(() => [
{ name: "admin", permissions: ["read", "write", "delete"] },
{ name: "editor", permissions: ["read", "write"] },
{ name: "viewer", permissions: ["read"] },
])
@RegisterTable("roles", "main")
class Role extends Table {
@Field("string")
declare name: string;
@Field(["string"])
declare permissions: string[];
}
export { Role };
Each RegisterSchema call inserts the fixture records into a table that is empty, and skips a table that already has rows. If you delete every row, the next start inserts the fixtures again. Use fixtures for lookup tables, default roles, or other data that must exist before the application serves requests.