Skip to content

Commit

Permalink
docs: Add Mikro ORM documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
Romakita committed Dec 30, 2021
1 parent 93f06ef commit ec00c75
Show file tree
Hide file tree
Showing 12 changed files with 245 additions and 68 deletions.
6 changes: 6 additions & 0 deletions docs/.vuepress/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,10 @@ module.exports = {
text: "Prisma",
link: "/tutorials/prisma.html"
},
{
text: "MikroORM",
link: "/tutorials/mikroorm.html"
},
{
text: "TypeORM",
link: "/tutorials/typeorm.html"
Expand Down Expand Up @@ -365,6 +369,7 @@ module.exports = {
"/tutorials/passport",
"/tutorials/keycloak",
"/tutorials/prisma",
// "/tutorials/mikroorm",
"/tutorials/typeorm",
"/tutorials/mongoose",
"/tutorials/graphql",
Expand Down Expand Up @@ -398,6 +403,7 @@ module.exports = {
"/tutorials/keycloak",
"/tutorials/prisma",
"/tutorials/typeorm",
// "/tutorials/mikroorm",
"/tutorials/mongoose",
"/tutorials/graphql",
"/tutorials/socket-io",
Expand Down
1 change: 0 additions & 1 deletion docs/.vuepress/enhanceApp.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import VueAnalytics from "vue-analytics";
import VueTsED from "vuepress-theme-tsed/src/install";
import "./styles/style.css";
// import {ReleaseNote} from "@tsed/vuepress-common";
import 'prismjs/components/prism-groovy';

export default ({
Expand Down
5 changes: 3 additions & 2 deletions docs/.vuepress/scripts/addWorkerScript.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,8 @@ parentPort.once('message', async payload => {
`Worker #${payload.workerNumber} error rendering ${pagePath}:`
),
false
)
),
e
)
throw e
} finally {
Expand Down Expand Up @@ -141,4 +142,4 @@ function renderPageMeta(meta) {
return res + `>`
})
.join('')
}
}
4 changes: 2 additions & 2 deletions docs/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -64,10 +64,10 @@
"millify": "^3.5.0"
},
"devDependencies": {
"@tsed/markdown-it-symbols": "3.12.1",
"@tsed/markdown-it-symbols": "3.16.1",
"vue-analytics": "5.22.1",
"vuepress": "1.8.2",
"vuepress-theme-tsed": "3.15.0"
"vuepress-theme-tsed": "3.16.1"
},
"directories": {
"packages": "packages",
Expand Down
31 changes: 5 additions & 26 deletions docs/readme.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ gettingStartedUrl: /getting-started/
messengerText: Discussions
messengerIcon: bxl-slack
messengerUrl: https://api.tsed.io/rest/slack/tsedio/tsed
sponsorText: Sponsor @romakita
sponsorUrl: https://github.com/sponsors/Romakita
features:
- title: Rest API
icon: bx-server
Expand Down Expand Up @@ -70,32 +72,6 @@ sponsors:
- title: Artips
href: https://artips.fr
src: /they-use-it/artips.png
- title: Sponsors
position: after-backers
class: px-3 py-2
style:
maxHeight: 30px
items:
- title: PnxBet
href: https://pnxbet.com.ph/
expireAt: 2021-12-14
src: /sponsors/pnxbet-ph-logo.png
- title: BestOnlineCasino.com.ph
href: https://bestonlinecasino.com.ph/
expireAt: 2021-12-14
src: /sponsors/BestOnlineCasino.png
- title: SportBetting
href: https://sportbetting.ph
expireAt: 2021-12-14
src: /sponsors/sportsbeting-1.png
- title: OnlineGambling
href: https://onlinegambling.com.ph/
expireAt: 2021-12-14
src: /sponsors/OnlineGambling.png
- title: https://best-casinos.in/
href: https://best-casinos.in/
expireAt: 2021-12-14
src: /sponsors/best-casinos-in-for-white-300x100.png
showContent: false
frameworks:
- title: TypeScript
Expand Down Expand Up @@ -134,6 +110,9 @@ frameworks:
- title: Prisma
href: /tutorials/prisma.html
src: /prisma-3.svg
- title: MikroORM
href: /tutorials/mikroorm.html
src: https://mikro-orm.io/img/logo.svg
- title: TypeORM
href: /tutorials/typeorm.html
src: /typeorm.png
Expand Down
195 changes: 195 additions & 0 deletions docs/tutorials/mikroorm.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,195 @@
---
meta:
- name: description
content: Use Mikro ORM with Ts.ED. TypeScript ORM for Node.js based on Data Mapper, Unit of Work and Identity Map patterns. Supports MongoDB, MySQL, MariaDB, PostgreSQL and SQLite databases..
- name: keywords
content: ts.ed express typescript mikro orm node.js javascript decorators
---

# MikroORM

<Banner src="https://raw.githubusercontent.com/mikro-orm/mikro-orm/master/docs/static/img/logo-readme.svg?sanitize=true" href="https://typeorm.io/" height="200" />

## Features

Currently, `@tsed/mikro-orm` allows you:

- Configure one or more MikroORM connections via the `@Configuration` decorator. All databases will be initialized when
the server starts during the server's `OnInit` phase.
- Use the Entity MikroORM as Model for Controllers, AJV Validation and Swagger.

## Installation

To begin, install the MikroORM module for TS.ED:

```bash
npm install --save @tsed/mikro-orm
npm install --save @mikro-orm/core
```

Then import `@tsed/mikro-orm` in your Server:

```typescript
import {Configuration} from "@tsed/common";
import {MikroOrmModule} from "@tsed/mikro-orm";

@Configuration({
imports: [MikroOrmModule],
mikroOrm: [
{
contextName: 'default',
type: 'postgres',
...,

entities: [
`${__dirname}/entity/*{.ts,.js}`
]
},
{
contextName: 'mongo',
type: 'mongo',
...
}
]
})
export class Server {

}
```

For more information about MikroORM look his documentation [here](https://mikro-orm.io/docs);

## Obtain a connection

`Connection` decorator lets you retrieve an instance of MikroORM Connection.

```typescript
import {Injectable, AfterRoutesInit} from "@tsed/common";
import {Connection} from "@tsed/mikro-orm";
import {MikroORM} from "@mikro-orm/core";

@Injectable()
export class UsersService {
@Connection()
private readonly connection!: MikroORM;

async create(user: User): Promise<User> {

// do something
// ...
// Then save
await this.connection.em.persistAndFlush(user);
console.log("Saved a new user with id: " + user.id);

return user;
}

async find(): Promise<User[]> {
const users = await this.connection.em.find(User, {});
console.log("Loaded users: ", users);

return users;
}
}
```

## Use Entity with Controller

To begin, we need to define an Entity MikroORM like this and use Ts.ED Decorator to define the JSON Schema.

```typescript
import {Property, MaxLength, Required} from "@tsed/common";
import {Entity, Property, PrimaryKey, Property as Column} from "@mikro-orm/core";

@Entity()
export class User {
@PrimaryKey()
@Property()
id: number;

@Column()
@MaxLength(100)
@Required()
firstName: string;

@Column()
@MaxLength(100)
@Required()
lastName: string;

@Column()
@Mininum(0)
@Maximum(100)
age: number;
}
```

Now, the model is correctly defined and can be used with a [Controller](https://tsed.io/docs/controllers.html)
, [AJV validation](tutorials/ajv.md),
[Swagger](tutorials/swagger.md) and [MikroORM](https://mikro-orm.io/docs/defining-entities).

We can use this model with a Controller like that:

```typescript
import {Controller, Post, BodyParams, Inject, Post, Get} from "@tsed/common";

@Controller("/users")
export class UsersCtrl {
@Inject()
private usersService: UsersService;

@Post("/")
create(@BodyParams() user: User): Promise<User> {
return this.usersService.create(user);
}

@Get("/")
getList(): Promise<User[]> {
return this.usersService.find();
}
}
```

## Transactions and Request context

As mentioned in the [docs](https://mikro-orm.io/docs/identity-map), we need to isolate a state for each request. That is
handled automatically thanks to the `AsyncLocalStorage` registered via interceptor.

We can use the `@Transactional()` decorator, which will register a new request context for your method and execute it
inside the context.

```typescript
import {Controller, Post, BodyParams, Inject, Get} from "@tsed/common";
import {Transactional} from "@tsed/mikro-orm";

@Controller("/users")
export class UsersCtrl {
@Inject()
private usersService: UsersService;

@Post("/")
@Transactional()
create(@BodyParams() user: User): Promise<User> {
return this.usersService.create(user);
}

@Get("/")
getList(): Promise<User[]> {
return this.usersService.find();
}
}
```

## Author

<GithubContributors :users="['derevnjuk']"/>

## Maintainers

<GithubContributors :users="['derevnjuk']"/>

<div class="flex items-center justify-center p-5">
<Button href="/contributing.html" class="rounded-medium">
Become maintainer
</Button>
</div>
11 changes: 1 addition & 10 deletions docs/tutorials/typeorm.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
meta:
- name: description
content: Use TypeORM with Express, TypeScript and Ts.ED. ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.
content: Use TypeORM with Ts.ED. ORM for TypeScript and JavaScript (ES7, ES6, ES5). Supports MySQL, PostgreSQL, MariaDB, SQLite, MS SQL Server, Oracle, WebSQL databases. Works in NodeJS, Browser, Ionic, Cordova and Electron platforms.
- name: keywords
content: ts.ed express typescript typeorm node.js javascript decorators
projects:
Expand All @@ -13,15 +13,6 @@ projects:

<Banner src="https://github.com/typeorm/typeorm/raw/master/resources/logo_big.png" href="https://typeorm.io/" height="200" />

This tutorial provides two ways to create connection:

- The first one uses @tsed/typeorm module to create multiple connections with @@Configuration@@,
- The second uses the new async provider feature introduced in v5.27 to create connection.

Additionally, this topic shows you how you can use Entity from Typeorm with Ts.ED controller (on the bottom of this page).

<Projects type="projects"/>

## Features

Currently, `@tsed/typeorm` allows you to:
Expand Down
Loading

0 comments on commit ec00c75

Please sign in to comment.