undeexcepturi
Version:
TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, PostgreSQL and SQLite databases as well as usage with vanilla JavaScript.
115 lines (82 loc) • 2.62 kB
text/typescript
import { Entity, PrimaryKey, Property, Embedded, Opt, SerializedPrimaryKey, Embeddable } from '@mikro-orm/core';
import { ObjectId, MikroORM, wrap } from '@mikro-orm/mongodb';
()
class StripeSubscription {
()
id!: string;
()
start!: Date;
()
end!: Date;
({ type: 'string' })
status!: string;
}
()
class StripeSubscription2 {
()
stripeId!: string;
()
start!: Date;
()
end!: Date;
({ type: 'string' })
status!: string;
}
()
class User {
()
_id!: ObjectId;
()
id!: string;
()
name: string;
({ unique: true })
email: string;
(() => StripeSubscription, { array: true })
stripeSubscriptions: StripeSubscription[] & Opt = [];
(() => StripeSubscription2, { array: true })
stripeSubscriptions2: StripeSubscription2[] & Opt = [];
constructor(name: string, email: string) {
this.name = name;
this.email = email;
}
}
let orm: MikroORM;
beforeAll(async () => {
orm = await MikroORM.init({
clientUrl: 'mongodb://localhost:27017/mikro_orm_4960',
entities: [User, StripeSubscription, StripeSubscription2],
});
await orm.schema.refreshDatabase();
});
afterAll(async () => {
await orm.close(true);
});
test('basic CRUD example', async () => {
orm.em.create(User, { name: 'Foo', email: 'foo' });
await orm.em.flush();
orm.em.clear();
const user = await orm.em.findOneOrFail(User, { email: 'foo' });
expect(user.name).toBe('Foo');
user.name = 'Bar';
orm.em.remove(user);
await orm.em.flush();
const count = await orm.em.count(User, { email: 'foo' });
expect(count).toBe(0);
});
test('Test Embeddabled', async () => {
const user = orm.em.create(User, { name: 'Foo', email: 'foo' });
await orm.em.flush();
const sub1 = new StripeSubscription();
wrap(sub1).assign({ id: 'aaa', start: new Date(), end: new Date(), status: 'ok' });
user.stripeSubscriptions = [...user.stripeSubscriptions, sub1];
const sub2 = new StripeSubscription2();
wrap(sub2).assign({ stripeId: 'aaa', start: new Date(), end: new Date(), status: 'ok' });
user.stripeSubscriptions2 = [...user.stripeSubscriptions2, sub2];
await orm.em.flush();
expect(user.stripeSubscriptions[0].id).toBe('aaa');
expect(user.stripeSubscriptions2[0].stripeId).toBe('aaa');
const user2 = await orm.em.findOneOrFail(User, { email: 'foo' });
expect(user2.stripeSubscriptions[0].id).toBe('aaa');
expect(user2.stripeSubscriptions2[0].stripeId).toBe('aaa');
});