@ledomsw/florm v0.1.2
flORM
A Fast, Lightweight ORM for JavaScript with TypeScript support
NOTE: The package shouldn't be used in production yet, at least until 1.x is released.
Installation
As simple as installing the NPM package with your favorite package manager:
npm i @ledomsw/florm
or
yarn add @ledomsw/florm
This package includes TypeScript type definitions!
Usage
Let's suppose you want to turn the following class into a flORM model:
class Person {
id: string = generateID();
name: string = '';
surname: string = '';
skills: string[] = [];
}
First, install the @ledomsw/florm
package and import the following:
import { FieldFlag, fld, Model, model } from '@ledomsw/florm';
Then, add a special static field to your class named new
as shown:
class Person {
// ... id, name, ...
static new = model(Person);
// ā Person is the name of the class itself
}
And finally replace the fields with flORM declarations as shown:
class Person {
id = fld.auto(generateID, FieldFlag.primaryKey);
name = fld.string();
surname = fld.string();
skills = fld.array.string();
static new = model(Person);
}
š Congratulations, your Person
class is now a flORM model!
To create instances of your model simply call new
:
// With defaults:
let someone = Person.new();
// With your field values:
let john = Person.new({ name: 'John', surname: 'Doe' });
And if you want a TypeScript interface for your model:
export interface IPerson extends Model<Person> {};
IMPORTANT: Always create new instances using the .new()
method! Instances created with the vanilla constructor (new Person()
) won't work!
Every flORM model instance exposes some utility methods to interact with the model and manipulate its fields, including:
with(props)
to set the value of one or more fields in the instance;pick(...fields)
to get a copy of the model instance with only the fields you want;except(...fields)
to get a copy of the model instance without the fields you don't want;pojo()
to create a POJO (Plain Old JavaScript Object) of the model instance, that is, a copy of the instance without the utility functions (great for API responses and serialization).
For example, you could use the pick
and pojo
methods to clean model instances before sending them in an API response:
function getPersonByIdEndpoint(req: Request, res: Response) {
// Always use your interface instead of the class type!
const person: IPerson | null = findPersonById(req.query.id);
if (person)
return res.send(person.except('dateOfBirth').pojo());
return res.status(404).end();
}