We'll be using an ORM called Sequelize to manage the connection to our database. We'll cover the basics in this concept, but Sequelize is a powerful tool and is extremely well documented at http://docs.sequelizejs.com/
Models
A model is the data representation of some group of data. In object-oriented programing terms, a model is an object and is represented by a new class. It should usually represent a noun such as a user, a feed item, an order, etc. We use the @Table
decorator and extend the base sequelize Model
class to link our model to our database table.
Parameters
The model contains instance parameters. These can be other models or primitive fields. We use the @Column
decorator to link our parameters to the table columns. The bang symbol !
specifies if the field in the table can be null. Sequelize handles the datatype mappings from TypeScript types to Postgres column datatypes.
Read more at the Sequelize docs entry on models.
Model:
import {Table, Column, Model, HasMany, PrimaryKey, CreatedAt, UpdatedAt, ForeignKey} from 'sequelize-typescript'; import { User } from '../../users/models/User'; @Table export class FeedItem extends Model<FeedItem> { @Column public caption!: string; @Column public url!: string; @Column @CreatedAt public createdAt: Date = new Date(); @Column @UpdatedAt public updatedAt: Date = new Date(); }
Usage:
const items = await FeedItem.findAndCountAll({ order: [["id", "DESC"]] }); const feed = await FeedItem.findByPk(id); const item = await new FeedItem({ caption: caption, url: fileName, }); const saved_item = await item.save();
Decorators
The Decorators (also known as Annotations) mentioned in this video are a feature of the sequelize-typescript package which allows us to link database features with our models. We exemplify this using the @CreatedAt
and @UpdatedAt
. This will set the option in the Postgres database to automatically set the date when any row is created, or updated and is useful when sorting and filtering our data.
Read more and view complete details on the model definition in the sequelize-typescript docs