import { Prorm, DataTypes, Op } from 'ts-prorm-orm';
const prorm = new Prorm({ dialect: 'sqlite', storage: ':memory:', logging: false });
// 1 Models, 2 Data types, 7 Validation
const User = prorm.define('User', {
id: { type: DataTypes.INTEGER(), primaryKey: true, autoIncrement: true },
email: { type: DataTypes.STRING(255), allowNull: false, unique: true, validate: { isEmail: true } },
}, { tableName: 'users' });
const Post = prorm.define('Post', {
id: { type: DataTypes.INTEGER(), primaryKey: true, autoIncrement: true },
title: { type: DataTypes.STRING(200), allowNull: false, validate: { len: [3, 200] } },
published: { type: DataTypes.BOOLEAN(), defaultValue: false },
userId: { type: DataTypes.INTEGER(), allowNull: false },
}, {
tableName: 'posts',
// 8 Hooks
hooks: {
beforeCreate: (post: any) => { // the values object, not yet a Model (see Hooks)
post.title = String(post.title).trim(); // plain values object before INSERT
},
},
});
// 5 Associations: declared before connect(), so sync() writes the REFERENCES
User.hasMany(Post, { foreignKey: 'userId', as: 'posts' });
Post.belongsTo(User, { foreignKey: 'userId', as: 'author' });
await prorm.connect();
await prorm.sync(); // 10 Migrations replace this once the data matters
// 9 Transactions: both rows or neither
await prorm.transaction(async (t) => {
const ada = await User.create({ email: 'ada@example.com' }, { transaction: t });
await Post.create({ title: ' Notes on the engine ', userId: ada.id, published: true }, { transaction: t });
});
// 3 Querying, 4 Query operators, 6 Eager loading
const authors = await User.findAll({
where: { email: { [Op.like]: '%@example.com' } },
include: [{ model: Post, as: 'posts', where: { published: true } }],
});
console.log(authors[0].posts[0].title); // 'Notes on the engine'