@mikro-orm/decorators 7.0.0-dev.64
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +390 -0
- package/es/Check.d.ts +2 -0
- package/es/Check.js +8 -0
- package/es/CreateRequestContext.d.ts +3 -0
- package/es/CreateRequestContext.js +29 -0
- package/es/Embeddable.d.ts +2 -0
- package/es/Embeddable.js +11 -0
- package/es/Embedded.d.ts +2 -0
- package/es/Embedded.js +15 -0
- package/es/Entity.d.ts +2 -0
- package/es/Entity.js +11 -0
- package/es/Enum.d.ts +2 -0
- package/es/Enum.js +14 -0
- package/es/Filter.d.ts +2 -0
- package/es/Filter.js +7 -0
- package/es/Formula.d.ts +2 -0
- package/es/Formula.js +13 -0
- package/es/Indexed.d.ts +3 -0
- package/es/Indexed.js +17 -0
- package/es/ManyToMany.d.ts +2 -0
- package/es/ManyToMany.js +12 -0
- package/es/ManyToOne.d.ts +2 -0
- package/es/ManyToOne.js +11 -0
- package/es/OneToMany.d.ts +3 -0
- package/es/OneToMany.js +12 -0
- package/es/OneToOne.d.ts +2 -0
- package/es/OneToOne.js +13 -0
- package/es/PrimaryKey.d.ts +3 -0
- package/es/PrimaryKey.js +17 -0
- package/es/Property.d.ts +2 -0
- package/es/Property.js +31 -0
- package/es/Transactional.d.ts +15 -0
- package/es/Transactional.js +27 -0
- package/es/hooks.d.ts +16 -0
- package/es/hooks.js +45 -0
- package/es/index.d.ts +17 -0
- package/es/index.js +17 -0
- package/legacy/Check.d.ts +2 -0
- package/legacy/Check.js +12 -0
- package/legacy/CreateRequestContext.d.ts +3 -0
- package/legacy/CreateRequestContext.js +31 -0
- package/legacy/Embeddable.d.ts +2 -0
- package/legacy/Embeddable.js +11 -0
- package/legacy/Embedded.d.ts +2 -0
- package/legacy/Embedded.js +14 -0
- package/legacy/Entity.d.ts +2 -0
- package/legacy/Entity.js +11 -0
- package/legacy/Enum.d.ts +2 -0
- package/legacy/Enum.js +13 -0
- package/legacy/Filter.d.ts +2 -0
- package/legacy/Filter.js +7 -0
- package/legacy/Formula.d.ts +2 -0
- package/legacy/Formula.js +12 -0
- package/legacy/Indexed.d.ts +3 -0
- package/legacy/Indexed.js +19 -0
- package/legacy/ManyToMany.d.ts +2 -0
- package/legacy/ManyToMany.js +10 -0
- package/legacy/ManyToOne.d.ts +2 -0
- package/legacy/ManyToOne.js +10 -0
- package/legacy/OneToMany.d.ts +3 -0
- package/legacy/OneToMany.js +10 -0
- package/legacy/OneToOne.d.ts +2 -0
- package/legacy/OneToOne.js +12 -0
- package/legacy/PrimaryKey.d.ts +3 -0
- package/legacy/PrimaryKey.js +16 -0
- package/legacy/Property.d.ts +2 -0
- package/legacy/Property.js +28 -0
- package/legacy/ReflectMetadataProvider.d.ts +6 -0
- package/legacy/ReflectMetadataProvider.js +39 -0
- package/legacy/Transactional.d.ts +15 -0
- package/legacy/Transactional.js +29 -0
- package/legacy/hooks.d.ts +16 -0
- package/legacy/hooks.js +44 -0
- package/legacy/index.d.ts +18 -0
- package/legacy/index.js +18 -0
- package/package.json +66 -0
- package/resolveContextProvider.d.ts +14 -0
- package/resolveContextProvider.js +26 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2018 Martin Adámek
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
<h1 align="center">
|
|
2
|
+
<a href="https://mikro-orm.io"><img src="https://raw.githubusercontent.com/mikro-orm/mikro-orm/master/docs/static/img/logo-readme.svg?sanitize=true" alt="MikroORM" /></a>
|
|
3
|
+
</h1>
|
|
4
|
+
|
|
5
|
+
TypeScript ORM for Node.js based on Data Mapper, [Unit of Work](https://mikro-orm.io/docs/unit-of-work/) and [Identity Map](https://mikro-orm.io/docs/identity-map/) patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite (including libSQL) databases.
|
|
6
|
+
|
|
7
|
+
> Heavily inspired by [Doctrine](https://www.doctrine-project.org/) and [Hibernate](https://hibernate.org/).
|
|
8
|
+
|
|
9
|
+
[](https://www.npmjs.com/package/@mikro-orm/core)
|
|
10
|
+
[](https://www.npmjs.com/package/@mikro-orm/core)
|
|
11
|
+
[](https://discord.gg/w8bjxFHS7X)
|
|
12
|
+
[](https://www.npmjs.com/package/@mikro-orm/core)
|
|
13
|
+
[](https://coveralls.io/r/mikro-orm/mikro-orm?branch=master)
|
|
14
|
+
[](https://github.com/mikro-orm/mikro-orm/actions?workflow=tests)
|
|
15
|
+
|
|
16
|
+
## 🤔 Unit of What?
|
|
17
|
+
|
|
18
|
+
You might be asking: _What the hell is Unit of Work and why should I care about it?_
|
|
19
|
+
|
|
20
|
+
> Unit of Work maintains a list of objects (_entities_) affected by a business transaction
|
|
21
|
+
> and coordinates the writing out of changes. [(Martin Fowler)](https://www.martinfowler.com/eaaCatalog/unitOfWork.html)
|
|
22
|
+
|
|
23
|
+
> Identity Map ensures that each object (_entity_) gets loaded only once by keeping every
|
|
24
|
+
> loaded object in a map. Looks up objects using the map when referring to them.
|
|
25
|
+
> [(Martin Fowler)](https://www.martinfowler.com/eaaCatalog/identityMap.html)
|
|
26
|
+
|
|
27
|
+
So what benefits does it bring to us?
|
|
28
|
+
|
|
29
|
+
### Implicit Transactions
|
|
30
|
+
|
|
31
|
+
First and most important implication of having Unit of Work is that it allows handling transactions automatically.
|
|
32
|
+
|
|
33
|
+
When you call `em.flush()`, all computed changes are queried inside a database transaction (if supported by given driver). This means that you can control the boundaries of transactions simply by calling `em.persistLater()` and once all your changes are ready, calling `flush()` will run them inside a transaction.
|
|
34
|
+
|
|
35
|
+
> You can also control the transaction boundaries manually via `em.transactional(cb)`.
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
const user = await em.findOneOrFail(User, 1);
|
|
39
|
+
user.email = 'foo@bar.com';
|
|
40
|
+
const car = new Car();
|
|
41
|
+
user.cars.add(car);
|
|
42
|
+
|
|
43
|
+
// thanks to bi-directional cascading we only need to persist user entity
|
|
44
|
+
// flushing will create a transaction, insert new car and update user with new email
|
|
45
|
+
// as user entity is managed, calling flush() is enough
|
|
46
|
+
await em.flush();
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
### ChangeSet based persistence
|
|
50
|
+
|
|
51
|
+
MikroORM allows you to implement your domain/business logic directly in the entities. To maintain always valid entities, you can use constructors to mark required properties. Let's define the `User` entity used in previous example:
|
|
52
|
+
|
|
53
|
+
```typescript
|
|
54
|
+
@Entity()
|
|
55
|
+
export class User {
|
|
56
|
+
|
|
57
|
+
@PrimaryKey()
|
|
58
|
+
id!: number;
|
|
59
|
+
|
|
60
|
+
@Property()
|
|
61
|
+
name!: string;
|
|
62
|
+
|
|
63
|
+
@OneToOne(() => Address)
|
|
64
|
+
address?: Address;
|
|
65
|
+
|
|
66
|
+
@ManyToMany(() => Car)
|
|
67
|
+
cars = new Collection<Car>(this);
|
|
68
|
+
|
|
69
|
+
constructor(name: string) {
|
|
70
|
+
this.name = name;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
}
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
Now to create new instance of the `User` entity, we are forced to provide the `name`:
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
const user = new User('John Doe'); // name is required to create new user instance
|
|
80
|
+
user.address = new Address('10 Downing Street'); // address is optional
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Once your entities are loaded, make a number of synchronous actions on your entities,
|
|
84
|
+
then call `em.flush()`. This will trigger computing of change sets. Only entities
|
|
85
|
+
(and properties) that were changed will generate database queries, if there are no changes,
|
|
86
|
+
no transaction will be started.
|
|
87
|
+
|
|
88
|
+
```typescript
|
|
89
|
+
const user = await em.findOneOrFail(User, 1, {
|
|
90
|
+
populate: ['cars', 'address.city'],
|
|
91
|
+
});
|
|
92
|
+
user.title = 'Mr.';
|
|
93
|
+
user.address.street = '10 Downing Street'; // address is 1:1 relation of Address entity
|
|
94
|
+
user.cars.getItems().forEach(car => car.forSale = true); // cars is 1:m collection of Car entities
|
|
95
|
+
const car = new Car('VW');
|
|
96
|
+
user.cars.add(car);
|
|
97
|
+
|
|
98
|
+
// now we can flush all changes done to managed entities
|
|
99
|
+
await em.flush();
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
`em.flush()` will then execute these queries from the example above:
|
|
103
|
+
|
|
104
|
+
```sql
|
|
105
|
+
begin;
|
|
106
|
+
update "user" set "title" = 'Mr.' where "id" = 1;
|
|
107
|
+
update "user_address" set "street" = '10 Downing Street' where "id" = 123;
|
|
108
|
+
update "car"
|
|
109
|
+
set "for_sale" = case
|
|
110
|
+
when ("id" = 1) then true
|
|
111
|
+
when ("id" = 2) then true
|
|
112
|
+
when ("id" = 3) then true
|
|
113
|
+
else "for_sale" end
|
|
114
|
+
where "id" in (1, 2, 3)
|
|
115
|
+
insert into "car" ("brand", "owner") values ('VW', 1);
|
|
116
|
+
commit;
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
### Identity Map
|
|
120
|
+
|
|
121
|
+
Thanks to Identity Map, you will always have only one instance of given entity in one context. This allows for some optimizations (skipping loading of already loaded entities), as well as comparison by identity (`ent1 === ent2`).
|
|
122
|
+
|
|
123
|
+
## 📖 Documentation
|
|
124
|
+
|
|
125
|
+
MikroORM documentation, included in this repo in the root directory, is built with [Docusaurus](https://docusaurus.io) and publicly hosted on GitHub Pages at https://mikro-orm.io.
|
|
126
|
+
|
|
127
|
+
There is also auto-generated [CHANGELOG.md](CHANGELOG.md) file based on commit messages (via `semantic-release`).
|
|
128
|
+
|
|
129
|
+
## ✨ Core Features
|
|
130
|
+
|
|
131
|
+
- [Clean and Simple Entity Definition](https://mikro-orm.io/docs/defining-entities)
|
|
132
|
+
- [Identity Map](https://mikro-orm.io/docs/identity-map)
|
|
133
|
+
- [Entity References](https://mikro-orm.io/docs/entity-references)
|
|
134
|
+
- [Using Entity Constructors](https://mikro-orm.io/docs/entity-constructors)
|
|
135
|
+
- [Modelling Relationships](https://mikro-orm.io/docs/relationships)
|
|
136
|
+
- [Collections](https://mikro-orm.io/docs/collections)
|
|
137
|
+
- [Unit of Work](https://mikro-orm.io/docs/unit-of-work)
|
|
138
|
+
- [Transactions](https://mikro-orm.io/docs/transactions)
|
|
139
|
+
- [Cascading persist and remove](https://mikro-orm.io/docs/cascading)
|
|
140
|
+
- [Composite and Foreign Keys as Primary Key](https://mikro-orm.io/docs/composite-keys)
|
|
141
|
+
- [Filters](https://mikro-orm.io/docs/filters)
|
|
142
|
+
- [Using `QueryBuilder`](https://mikro-orm.io/docs/query-builder)
|
|
143
|
+
- [Populating relations](https://mikro-orm.io/docs/populating-relations)
|
|
144
|
+
- [Property Validation](https://mikro-orm.io/docs/property-validation)
|
|
145
|
+
- [Lifecycle Hooks](https://mikro-orm.io/docs/events#hooks)
|
|
146
|
+
- [Vanilla JS Support](https://mikro-orm.io/docs/usage-with-js)
|
|
147
|
+
- [Schema Generator](https://mikro-orm.io/docs/schema-generator)
|
|
148
|
+
- [Entity Generator](https://mikro-orm.io/docs/entity-generator)
|
|
149
|
+
|
|
150
|
+
## 📦 Example Integrations
|
|
151
|
+
|
|
152
|
+
You can find example integrations for some popular frameworks in the [`mikro-orm-examples` repository](https://github.com/mikro-orm/mikro-orm-examples):
|
|
153
|
+
|
|
154
|
+
### TypeScript Examples
|
|
155
|
+
|
|
156
|
+
- [Express + MongoDB](https://github.com/mikro-orm/express-ts-example-app)
|
|
157
|
+
- [Nest + MySQL](https://github.com/mikro-orm/nestjs-example-app)
|
|
158
|
+
- [RealWorld example app (Nest + MySQL)](https://github.com/mikro-orm/nestjs-realworld-example-app)
|
|
159
|
+
- [Koa + SQLite](https://github.com/mikro-orm/koa-ts-example-app)
|
|
160
|
+
- [GraphQL + PostgreSQL](https://github.com/driescroons/mikro-orm-graphql-example)
|
|
161
|
+
- [Inversify + PostgreSQL](https://github.com/PodaruDragos/inversify-example-app)
|
|
162
|
+
- [NextJS + MySQL](https://github.com/jonahallibone/mikro-orm-nextjs)
|
|
163
|
+
- [Accounts.js REST and GraphQL authentication + SQLite](https://github.com/darkbasic/mikro-orm-accounts-example)
|
|
164
|
+
- [Nest + Shopify + PostgreSQL + GraphQL](https://github.com/Cloudshelf/Shopify_CSConnector)
|
|
165
|
+
- [Elysia.js + libSQL + Bun](https://github.com/mikro-orm/elysia-bun-example-app)
|
|
166
|
+
- [Electron.js + PostgreSQL](https://github.com/adnanlah/electron-mikro-orm-example-app)
|
|
167
|
+
|
|
168
|
+
### JavaScript Examples
|
|
169
|
+
|
|
170
|
+
- [Express + SQLite](https://github.com/mikro-orm/express-js-example-app)
|
|
171
|
+
|
|
172
|
+
## 🚀 Quick Start
|
|
173
|
+
|
|
174
|
+
First install the module via `yarn` or `npm` and do not forget to install the database driver as well:
|
|
175
|
+
|
|
176
|
+
> Since v4, you should install the driver package, but not the db connector itself, e.g. install `@mikro-orm/sqlite`, but not `sqlite3` as that is already included in the driver package.
|
|
177
|
+
|
|
178
|
+
```sh
|
|
179
|
+
yarn add @mikro-orm/core @mikro-orm/mongodb # for mongo
|
|
180
|
+
yarn add @mikro-orm/core @mikro-orm/mysql # for mysql/mariadb
|
|
181
|
+
yarn add @mikro-orm/core @mikro-orm/mariadb # for mysql/mariadb
|
|
182
|
+
yarn add @mikro-orm/core @mikro-orm/postgresql # for postgresql
|
|
183
|
+
yarn add @mikro-orm/core @mikro-orm/mssql # for mssql
|
|
184
|
+
yarn add @mikro-orm/core @mikro-orm/sqlite # for sqlite
|
|
185
|
+
yarn add @mikro-orm/core @mikro-orm/libsql # for libsql
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
or
|
|
189
|
+
|
|
190
|
+
```sh
|
|
191
|
+
npm i -s @mikro-orm/core @mikro-orm/mongodb # for mongo
|
|
192
|
+
npm i -s @mikro-orm/core @mikro-orm/mysql # for mysql/mariadb
|
|
193
|
+
npm i -s @mikro-orm/core @mikro-orm/mariadb # for mysql/mariadb
|
|
194
|
+
npm i -s @mikro-orm/core @mikro-orm/postgresql # for postgresql
|
|
195
|
+
npm i -s @mikro-orm/core @mikro-orm/mssql # for mssql
|
|
196
|
+
npm i -s @mikro-orm/core @mikro-orm/sqlite # for sqlite
|
|
197
|
+
npm i -s @mikro-orm/core @mikro-orm/libsql # for libsql
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
Next, if you want to use decorators for your entity definition, you will need to enable support for [decorators](https://www.typescriptlang.org/docs/handbook/decorators.html) as well as `esModuleInterop` in `tsconfig.json` via:
|
|
201
|
+
|
|
202
|
+
```json
|
|
203
|
+
"experimentalDecorators": true,
|
|
204
|
+
"emitDecoratorMetadata": true,
|
|
205
|
+
"esModuleInterop": true,
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Alternatively, you can use [`EntitySchema`](https://mikro-orm.io/docs/entity-schema).
|
|
209
|
+
|
|
210
|
+
Then call `MikroORM.init` as part of bootstrapping your app:
|
|
211
|
+
|
|
212
|
+
> To access driver specific methods like `em.createQueryBuilder()` we need to specify the driver type when calling `MikroORM.init()`. Alternatively we can cast the `orm.em` to `EntityManager` exported from the driver package:
|
|
213
|
+
>
|
|
214
|
+
> ```ts
|
|
215
|
+
> import { EntityManager } from '@mikro-orm/postgresql';
|
|
216
|
+
> const em = orm.em as EntityManager;
|
|
217
|
+
> const qb = em.createQueryBuilder(...);
|
|
218
|
+
> ```
|
|
219
|
+
|
|
220
|
+
```typescript
|
|
221
|
+
import type { PostgreSqlDriver } from '@mikro-orm/postgresql'; // or any other SQL driver package
|
|
222
|
+
|
|
223
|
+
const orm = await MikroORM.init<PostgreSqlDriver>({
|
|
224
|
+
entities: ['./dist/entities'], // path to your JS entities (dist), relative to `baseDir`
|
|
225
|
+
dbName: 'my-db-name',
|
|
226
|
+
type: 'postgresql',
|
|
227
|
+
});
|
|
228
|
+
console.log(orm.em); // access EntityManager via `em` property
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
There are more ways to configure your entities, take a look at [installation page](https://mikro-orm.io/docs/installation/).
|
|
232
|
+
|
|
233
|
+
> Read more about all the possible configuration options in [Advanced Configuration](https://mikro-orm.io/docs/configuration) section.
|
|
234
|
+
|
|
235
|
+
Then you will need to fork entity manager for each request so their [identity maps](https://mikro-orm.io/docs/identity-map/) will not collide. To do so, use the `RequestContext` helper:
|
|
236
|
+
|
|
237
|
+
```typescript
|
|
238
|
+
const app = express();
|
|
239
|
+
|
|
240
|
+
app.use((req, res, next) => {
|
|
241
|
+
RequestContext.create(orm.em, next);
|
|
242
|
+
});
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
> You should register this middleware as the last one just before request handlers and before any of your custom middleware that is using the ORM. There might be issues when you register it before request processing middleware like `queryParser` or `bodyParser`, so definitely register the context after them.
|
|
246
|
+
|
|
247
|
+
More info about `RequestContext` is described [here](https://mikro-orm.io/docs/identity-map/#request-context).
|
|
248
|
+
|
|
249
|
+
Now you can start defining your entities (in one of the `entities` folders). This is how simple entity can look like in mongo driver:
|
|
250
|
+
|
|
251
|
+
**`./entities/MongoBook.ts`**
|
|
252
|
+
|
|
253
|
+
```typescript
|
|
254
|
+
@Entity()
|
|
255
|
+
export class MongoBook {
|
|
256
|
+
|
|
257
|
+
@PrimaryKey()
|
|
258
|
+
_id: ObjectID;
|
|
259
|
+
|
|
260
|
+
@SerializedPrimaryKey()
|
|
261
|
+
id: string;
|
|
262
|
+
|
|
263
|
+
@Property()
|
|
264
|
+
title: string;
|
|
265
|
+
|
|
266
|
+
@ManyToOne(() => Author)
|
|
267
|
+
author: Author;
|
|
268
|
+
|
|
269
|
+
@ManyToMany(() => BookTag)
|
|
270
|
+
tags = new Collection<BookTag>(this);
|
|
271
|
+
|
|
272
|
+
constructor(title: string, author: Author) {
|
|
273
|
+
this.title = title;
|
|
274
|
+
this.author = author;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
}
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
For SQL drivers, you can use `id: number` PK:
|
|
281
|
+
|
|
282
|
+
**`./entities/SqlBook.ts`**
|
|
283
|
+
|
|
284
|
+
```typescript
|
|
285
|
+
@Entity()
|
|
286
|
+
export class SqlBook {
|
|
287
|
+
|
|
288
|
+
@PrimaryKey()
|
|
289
|
+
id: number;
|
|
290
|
+
|
|
291
|
+
}
|
|
292
|
+
```
|
|
293
|
+
|
|
294
|
+
Or if you want to use UUID primary keys:
|
|
295
|
+
|
|
296
|
+
**`./entities/UuidBook.ts`**
|
|
297
|
+
|
|
298
|
+
```typescript
|
|
299
|
+
import { randomUUID } from 'node:crypto';
|
|
300
|
+
|
|
301
|
+
@Entity()
|
|
302
|
+
export class UuidBook {
|
|
303
|
+
|
|
304
|
+
@PrimaryKey()
|
|
305
|
+
uuid = randomUUID();
|
|
306
|
+
|
|
307
|
+
}
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
More information can be found in [defining entities section](https://mikro-orm.io/docs/defining-entities/) in docs.
|
|
311
|
+
|
|
312
|
+
When you have your entities defined, you can start using ORM either via `EntityManager` or via `EntityRepository`s.
|
|
313
|
+
|
|
314
|
+
To save entity state to database, you need to persist it. Persist takes care or deciding whether to use `insert` or `update` and computes appropriate change-set. Entity references that are not persisted yet (does not have identifier) will be cascade persisted automatically.
|
|
315
|
+
|
|
316
|
+
```typescript
|
|
317
|
+
// use constructors in your entities for required parameters
|
|
318
|
+
const author = new Author('Jon Snow', 'snow@wall.st');
|
|
319
|
+
author.born = new Date();
|
|
320
|
+
|
|
321
|
+
const publisher = new Publisher('7K publisher');
|
|
322
|
+
|
|
323
|
+
const book1 = new Book('My Life on The Wall, part 1', author);
|
|
324
|
+
book1.publisher = publisher;
|
|
325
|
+
const book2 = new Book('My Life on The Wall, part 2', author);
|
|
326
|
+
book2.publisher = publisher;
|
|
327
|
+
const book3 = new Book('My Life on The Wall, part 3', author);
|
|
328
|
+
book3.publisher = publisher;
|
|
329
|
+
|
|
330
|
+
// just persist books, author and publisher will be automatically cascade persisted
|
|
331
|
+
await em.persistAndFlush([book1, book2, book3]);
|
|
332
|
+
```
|
|
333
|
+
|
|
334
|
+
To fetch entities from database you can use `find()` and `findOne()` of `EntityManager`:
|
|
335
|
+
|
|
336
|
+
```typescript
|
|
337
|
+
const authors = em.find(Author, {}, { populate: ['books'] });
|
|
338
|
+
|
|
339
|
+
for (const author of authors) {
|
|
340
|
+
console.log(author); // instance of Author entity
|
|
341
|
+
console.log(author.name); // Jon Snow
|
|
342
|
+
|
|
343
|
+
for (const book of author.books) { // iterating books collection
|
|
344
|
+
console.log(book); // instance of Book entity
|
|
345
|
+
console.log(book.title); // My Life on The Wall, part 1/2/3
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
More convenient way of fetching entities from database is by using `EntityRepository`, that carries the entity name, so you do not have to pass it to every `find` and `findOne` calls:
|
|
351
|
+
|
|
352
|
+
```typescript
|
|
353
|
+
const booksRepository = em.getRepository(Book);
|
|
354
|
+
|
|
355
|
+
const books = await booksRepository.find({ author: '...' }, {
|
|
356
|
+
populate: ['author'],
|
|
357
|
+
limit: 1,
|
|
358
|
+
offset: 2,
|
|
359
|
+
orderBy: { title: QueryOrder.DESC },
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
console.log(books); // Loaded<Book, 'author'>[]
|
|
363
|
+
```
|
|
364
|
+
|
|
365
|
+
Take a look at docs about [working with `EntityManager`](https://mikro-orm.io/docs/entity-manager/) or [using `EntityRepository` instead](https://mikro-orm.io/docs/repositories/).
|
|
366
|
+
|
|
367
|
+
## 🤝 Contributing
|
|
368
|
+
|
|
369
|
+
Contributions, issues and feature requests are welcome. Please read [CONTRIBUTING.md](CONTRIBUTING.md) for details on the process for submitting pull requests to us.
|
|
370
|
+
|
|
371
|
+
## Authors
|
|
372
|
+
|
|
373
|
+
👤 **Martin Adámek**
|
|
374
|
+
|
|
375
|
+
- Twitter: [@B4nan](https://twitter.com/B4nan)
|
|
376
|
+
- Github: [@b4nan](https://github.com/b4nan)
|
|
377
|
+
|
|
378
|
+
See also the list of contributors who [participated](https://github.com/mikro-orm/mikro-orm/contributors) in this project.
|
|
379
|
+
|
|
380
|
+
## Show Your Support
|
|
381
|
+
|
|
382
|
+
Please ⭐️ this repository if this project helped you!
|
|
383
|
+
|
|
384
|
+
> If you'd like to support my open-source work, consider sponsoring me directly at [github.com/sponsors/b4nan](https://github.com/sponsors/b4nan).
|
|
385
|
+
|
|
386
|
+
## 📝 License
|
|
387
|
+
|
|
388
|
+
Copyright © 2018 [Martin Adámek](https://github.com/b4nan).
|
|
389
|
+
|
|
390
|
+
This project is licensed under the MIT License - see the [LICENSE file](LICENSE) for details.
|
package/es/Check.d.ts
ADDED
package/es/Check.js
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { type ContextProvider } from '../resolveContextProvider.js';
|
|
2
|
+
export declare function CreateRequestContext<T extends object>(contextProvider?: ContextProvider<T>, respectExistingContext?: boolean): (value: (this: T, ...args: any) => any, context: ClassMethodDecoratorContext<T>) => (this: T, ...args: any[]) => Promise<any>;
|
|
3
|
+
export declare function EnsureRequestContext<T extends object>(context?: ContextProvider<T>): (value: (this: T, ...args: any) => any, context: ClassMethodDecoratorContext<T, (this: T, ...args: any) => any>) => (this: T, ...args: any[]) => Promise<any>;
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { RequestContext, TransactionContext } from '@mikro-orm/core';
|
|
2
|
+
import { resolveContextProvider } from '../resolveContextProvider.js';
|
|
3
|
+
export function CreateRequestContext(contextProvider, respectExistingContext = false) {
|
|
4
|
+
return function (value, context) {
|
|
5
|
+
const name = respectExistingContext ? 'EnsureRequestContext' : 'CreateRequestContext';
|
|
6
|
+
if (value.constructor.name !== 'AsyncFunction') {
|
|
7
|
+
throw new Error(`@${name}() should be use with async functions`);
|
|
8
|
+
}
|
|
9
|
+
return async function (...args) {
|
|
10
|
+
const em = await resolveContextProvider(this, contextProvider);
|
|
11
|
+
if (!em) {
|
|
12
|
+
throw new Error(`@${name}() decorator can only be applied to methods of classes with \`orm: MikroORM\` property, \`em: EntityManager\` property, or with a callback parameter like \`@${name}(() => orm)\` that returns one of those types. The parameter will contain a reference to current \`this\`. Returning an EntityRepository from it is also supported.`);
|
|
13
|
+
}
|
|
14
|
+
// reuse existing context if available for given respect `contextName`
|
|
15
|
+
if (respectExistingContext && RequestContext.getEntityManager(em.name)) {
|
|
16
|
+
return value.apply(this, args);
|
|
17
|
+
}
|
|
18
|
+
// Otherwise, the outer tx context would be preferred.
|
|
19
|
+
const txContext = TransactionContext.currentTransactionContext();
|
|
20
|
+
const provider = txContext ? TransactionContext : RequestContext;
|
|
21
|
+
return txContext
|
|
22
|
+
? provider.create(em.fork({ useContext: true }), () => value.apply(this, args))
|
|
23
|
+
: provider.create(em, () => value.apply(this, args));
|
|
24
|
+
};
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
export function EnsureRequestContext(context) {
|
|
28
|
+
return CreateRequestContext(context, true);
|
|
29
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { type Constructor, type EmbeddableOptions, type EntityClass } from '@mikro-orm/core';
|
|
2
|
+
export declare function Embeddable<Owner extends EntityClass<unknown> & Constructor>(options?: EmbeddableOptions<Owner>): (target: Owner, context: ClassDecoratorContext<Owner>) => Owner;
|
package/es/Embeddable.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { MetadataStorage, Utils, } from '@mikro-orm/core';
|
|
2
|
+
export function Embeddable(options = {}) {
|
|
3
|
+
return function (target, context) {
|
|
4
|
+
const meta = MetadataStorage.getMetadataFromDecorator(target);
|
|
5
|
+
Utils.mergeConfig(meta, context.metadata, options);
|
|
6
|
+
meta.class = target;
|
|
7
|
+
meta.name = meta.class.name;
|
|
8
|
+
meta.embeddable = true;
|
|
9
|
+
return target;
|
|
10
|
+
};
|
|
11
|
+
}
|
package/es/Embedded.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { type EntityName, type EmbeddedOptions } from '@mikro-orm/core';
|
|
2
|
+
export declare function Embedded<Owner extends object, Target>(type?: EmbeddedOptions<Owner, Target> | (() => EntityName<Target> | EntityName<Target>[]), options?: EmbeddedOptions<Owner, Target>): (value: unknown, context: ClassFieldDecoratorContext<Owner>) => void;
|
package/es/Embedded.js
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { MetadataValidator, ReferenceKind, Utils, } from '@mikro-orm/core';
|
|
2
|
+
export function Embedded(type = {}, options = {}) {
|
|
3
|
+
return function (value, context) {
|
|
4
|
+
const meta = context.metadata;
|
|
5
|
+
meta.properties ??= {};
|
|
6
|
+
MetadataValidator.validateSingleDecorator(meta, context.name, ReferenceKind.EMBEDDED);
|
|
7
|
+
options = type instanceof Function ? { entity: type, ...options } : { ...type, ...options };
|
|
8
|
+
Utils.defaultValue(options, 'prefix', true);
|
|
9
|
+
meta.properties[context.name] = {
|
|
10
|
+
name: context.name,
|
|
11
|
+
kind: ReferenceKind.EMBEDDED,
|
|
12
|
+
...options,
|
|
13
|
+
};
|
|
14
|
+
};
|
|
15
|
+
}
|
package/es/Entity.d.ts
ADDED
package/es/Entity.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { MetadataStorage, Utils, } from '@mikro-orm/core';
|
|
2
|
+
export function Entity(options = {}) {
|
|
3
|
+
return function (target, context) {
|
|
4
|
+
const meta = MetadataStorage.getMetadataFromDecorator(target);
|
|
5
|
+
Utils.mergeConfig(meta, context.metadata, options);
|
|
6
|
+
meta.class = target;
|
|
7
|
+
if (!options.abstract || meta.discriminatorColumn) {
|
|
8
|
+
meta.name = context.name;
|
|
9
|
+
}
|
|
10
|
+
};
|
|
11
|
+
}
|
package/es/Enum.d.ts
ADDED
package/es/Enum.js
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { ReferenceKind, } from '@mikro-orm/core';
|
|
2
|
+
export function Enum(options = {}) {
|
|
3
|
+
return function (target, context) {
|
|
4
|
+
const meta = context.metadata;
|
|
5
|
+
meta.properties ??= {};
|
|
6
|
+
options = options instanceof Function ? { items: options } : options;
|
|
7
|
+
meta.properties[context.name] = {
|
|
8
|
+
name: context.name,
|
|
9
|
+
kind: ReferenceKind.SCALAR,
|
|
10
|
+
enum: true,
|
|
11
|
+
...options,
|
|
12
|
+
};
|
|
13
|
+
};
|
|
14
|
+
}
|
package/es/Filter.d.ts
ADDED
package/es/Filter.js
ADDED
package/es/Formula.d.ts
ADDED
package/es/Formula.js
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { ReferenceKind, } from '@mikro-orm/core';
|
|
2
|
+
export function Formula(formula, options = {}) {
|
|
3
|
+
return function (value, context) {
|
|
4
|
+
const meta = context.metadata;
|
|
5
|
+
meta.properties ??= {};
|
|
6
|
+
meta.properties[context.name] = {
|
|
7
|
+
name: context.name,
|
|
8
|
+
kind: ReferenceKind.SCALAR,
|
|
9
|
+
formula,
|
|
10
|
+
...options,
|
|
11
|
+
};
|
|
12
|
+
};
|
|
13
|
+
}
|
package/es/Indexed.d.ts
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { type IndexOptions, type UniqueOptions, type Constructor } from '@mikro-orm/core';
|
|
2
|
+
export declare function Index<T extends object, H extends string>(options?: IndexOptions<T, H>): (value: unknown, context: ClassDecoratorContext<T & Constructor> | ClassFieldDecoratorContext<T, unknown>) => any;
|
|
3
|
+
export declare function Unique<T extends object, H extends string>(options?: UniqueOptions<T, H>): (value: unknown, context: ClassDecoratorContext<T & Constructor> | ClassFieldDecoratorContext<T, unknown>) => any;
|
package/es/Indexed.js
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
function createDecorator(options, unique) {
|
|
2
|
+
return function (value, context) {
|
|
3
|
+
const meta = context.metadata;
|
|
4
|
+
if (context.kind === 'field') {
|
|
5
|
+
options.properties ??= context.name;
|
|
6
|
+
}
|
|
7
|
+
const key = unique ? 'uniques' : 'indexes';
|
|
8
|
+
meta[key] ??= [];
|
|
9
|
+
meta[key].push(options);
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
export function Index(options = {}) {
|
|
13
|
+
return createDecorator(options, false);
|
|
14
|
+
}
|
|
15
|
+
export function Unique(options = {}) {
|
|
16
|
+
return createDecorator(options, true);
|
|
17
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { type EntityName, type ManyToManyOptions, type Collection } from '@mikro-orm/core';
|
|
2
|
+
export declare function ManyToMany<Target extends object, Owner extends object>(entity?: ManyToManyOptions<Owner, Target> | string | (() => EntityName<Target>), mappedBy?: (string & keyof Target) | ((e: Target) => any), options?: Partial<ManyToManyOptions<Owner, Target>>): (_: unknown, context: ClassFieldDecoratorContext<Owner, Collection<Target> | undefined>) => void;
|
package/es/ManyToMany.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { MetadataValidator, ReferenceKind, Utils, } from '@mikro-orm/core';
|
|
2
|
+
export function ManyToMany(entity, mappedBy, options = {}) {
|
|
3
|
+
return function (_, context) {
|
|
4
|
+
const meta = context.metadata;
|
|
5
|
+
meta.properties ??= {};
|
|
6
|
+
MetadataValidator.validateSingleDecorator(meta, context.name, ReferenceKind.MANY_TO_MANY);
|
|
7
|
+
options = Utils.processDecoratorParameters({ entity, mappedBy, options });
|
|
8
|
+
const property = { name: context.name, kind: ReferenceKind.MANY_TO_MANY };
|
|
9
|
+
meta.properties[context.name] ??= {};
|
|
10
|
+
Utils.mergeConfig(meta.properties[context.name], property, options);
|
|
11
|
+
};
|
|
12
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { type ManyToOneOptions, type EntityName, type Ref } from '@mikro-orm/core';
|
|
2
|
+
export declare function ManyToOne<Target extends object, Owner extends object>(entity?: ManyToOneOptions<Owner, Target> | string | ((e?: Owner) => EntityName<Target>), options?: Partial<ManyToOneOptions<Owner, Target>>): (_: unknown, context: ClassFieldDecoratorContext<Owner, Target | undefined | null | Ref<Target>>) => void;
|
package/es/ManyToOne.js
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { ReferenceKind, MetadataValidator, Utils, } from '@mikro-orm/core';
|
|
2
|
+
export function ManyToOne(entity = {}, options = {}) {
|
|
3
|
+
return function (_, context) {
|
|
4
|
+
const meta = context.metadata;
|
|
5
|
+
meta.properties ??= {};
|
|
6
|
+
MetadataValidator.validateSingleDecorator(meta, context.name, ReferenceKind.MANY_TO_ONE);
|
|
7
|
+
options = Utils.processDecoratorParameters({ entity, options });
|
|
8
|
+
const property = { name: context.name, kind: ReferenceKind.MANY_TO_ONE };
|
|
9
|
+
meta.properties[context.name] = Utils.mergeConfig(meta.properties[context.name] ?? {}, property, options);
|
|
10
|
+
};
|
|
11
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import { type Collection, type EntityName, type OneToManyOptions } from '@mikro-orm/core';
|
|
2
|
+
export declare function OneToMany<Target extends object, Owner extends object>(entity: string | ((e?: Owner) => EntityName<Target>), mappedBy: (string & keyof Target) | ((e: Target) => any), options?: Partial<OneToManyOptions<Owner, Target>>): (value: unknown, context: ClassFieldDecoratorContext<Owner, Collection<Target> | undefined>) => void;
|
|
3
|
+
export declare function OneToMany<Target extends object, Owner extends object>(options: OneToManyOptions<Owner, Target>): (value: unknown, context: ClassFieldDecoratorContext<Owner, Collection<Target> | undefined>) => void;
|
package/es/OneToMany.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { MetadataValidator, ReferenceKind, Utils, } from '@mikro-orm/core';
|
|
2
|
+
export function OneToMany(entity, mappedBy, options = {}) {
|
|
3
|
+
return function (value, context) {
|
|
4
|
+
const meta = context.metadata;
|
|
5
|
+
meta.properties ??= {};
|
|
6
|
+
MetadataValidator.validateSingleDecorator(meta, context.name, ReferenceKind.ONE_TO_MANY);
|
|
7
|
+
options = Utils.processDecoratorParameters({ entity, mappedBy, options });
|
|
8
|
+
const property = { name: context.name, kind: ReferenceKind.ONE_TO_MANY };
|
|
9
|
+
meta.properties[context.name] ??= {};
|
|
10
|
+
Utils.mergeConfig(meta.properties[context.name], property, options);
|
|
11
|
+
};
|
|
12
|
+
}
|
package/es/OneToOne.d.ts
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { type EntityName, type OneToOneOptions } from '@mikro-orm/core';
|
|
2
|
+
export declare function OneToOne<Target extends object, Owner extends object>(entity?: OneToOneOptions<Owner, Target> | string | ((e: Owner) => EntityName<Target>), mappedByOrOptions?: (string & keyof Target) | ((e: Target) => any) | Partial<OneToOneOptions<Owner, Target>>, options?: Partial<OneToOneOptions<Owner, Target>>): (_: unknown, context: ClassFieldDecoratorContext<Owner, Target>) => void;
|