Skip to content

Commit 38ea9b5

Browse files
committed
refactor(full): full rewrite
Removed the nitro plugin in favor of util functions, intended for use in custom Nitro plugins.
1 parent 7e6815f commit 38ea9b5

17 files changed

Lines changed: 668 additions & 248 deletions

File tree

.husky/commit-msg

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#!/bin/sh
2+
. "$(dirname "$0")/_/husky.sh"
3+
4+
yarn commitlint --edit $1

README.md

Lines changed: 15 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,17 +13,25 @@ Install the module to your Nuxt application with one command:
1313
npx nuxi module add nuxt-mikro-orm-module
1414
```
1515

16-
After that, a plugin needs to be created, which calls the "mikroOrm:create" hook.
17-
If multiple MikroORM instances are required, this hook may be called multiple times, with different names.
18-
The plugin should ideally call this hook before the server is ready.
16+
After that, ideally in a Nitro plugin, call initOrm() with the instance's config.
1917

20-
The hook "mikroOrm:init" will be called for every new instance.
18+
Call useEntityManager() in a request context to get a forked EntityManager you can immediately use.
19+
If you are working in a different context, such as a cron job, you may call useOrm(), and manually call `fork()` to get a locally scoped EntityManager.
2120

22-
## Helper functions
21+
## API
2322

24-
- `getEntityManager(name?: string)` - Get an entity manager with the current request context. Intended for use in server components.
25-
- `useOrm(name?: string)` - Get the MikroORM instance. Intended for use in server components.
23+
- `initOrm<T extends MikroOrmInstance = MikroOrmInstance>(config: ReturnType<typeof defineConfig>, name: string = 'default', forkOptionsFactory?: (event: H3Event<EventHandlerRequest>, name: string) => ForkOptions|undefined): Promise<T>` - Initialize a MikroORM instance with the given config. Optionally provide a name and fork options callback (called on each request where EntityManager is used; must not be async). Returns a promise that resolves with the initialized MikroORM instance.
24+
- `useEntityManager<T extends EntityManager = EntityManager>(event: H3Event<EventHandlerRequest>, name: string = 'default'): T` - Get an entity manager with the current request context.
25+
- `useOrm<T extends MikroOrmInstance = MikroOrmInstance>(name: string = 'default'): T` - Get the MikroORM instance.
26+
- `closeOrm(name: string = 'default', force: boolean = false)` - Close an existing MikroORM instance. The name also becomes available for reuse after close.
2627

28+
## Module options / Runtime options
29+
30+
This module's options are used as defaults for runtime options, under the `mikroOrm` key.
31+
32+
Available options:
33+
34+
- `forkOptions` - Default fork options when calling initOrm() without a `forkOptionsFactory`, or when the `forkOptionsFactory` function returns undefined.
2735

2836
## Contribution
2937

commitlint.config.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
export default { extends: ['@commitlint/config-conventional'] };

package.json

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,8 @@
2525
"lint": "eslint .",
2626
"test": "vitest run",
2727
"test:watch": "vitest watch",
28-
"test:types": "vue-tsc --noEmit && cd playground && vue-tsc --noEmit"
28+
"test:types": "vue-tsc --noEmit && cd playground && vue-tsc --noEmit",
29+
"prepare": "husky"
2930
},
3031
"dependencies": {
3132
"@nuxt/kit": "^3.11.2",
@@ -37,6 +38,8 @@
3738
"nitropack": "^2.9.6"
3839
},
3940
"devDependencies": {
41+
"@commitlint/cli": "^19.3.0",
42+
"@commitlint/config-conventional": "^19.2.2",
4043
"@mikro-orm/core": "*",
4144
"@mikro-orm/mysql": "*",
4245
"@nuxt/devtools": "^1.3.1",
@@ -48,6 +51,7 @@
4851
"changelogen": "^0.5.5",
4952
"cross-env": "^7.0.3",
5053
"eslint": "^8.57.0",
54+
"husky": "^9.0.11",
5155
"nuxi": "^3.11.1",
5256
"nuxt": "^3.11.2",
5357
"typescript": "latest",

playground/components/DbLog.server.vue

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,9 @@
55
</template>
66

77
<script setup lang="ts">
8-
import {type EntityManager} from "@mikro-orm/mysql";
8+
import { type EntityManager } from "@mikro-orm/mysql";
99
10-
const em: EntityManager = useEntityManager();
10+
const event = useRequestEvent()!;
11+
const em = useEntityManager<EntityManager>(event);
1112
const productName = (await em.execute<[{name: string}]>('SELECT name FROM products LIMIT 1'))[0].name;
1213
</script>
Lines changed: 28 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,36 @@
1-
import {defineConfig, type EntityManager} from "@mikro-orm/mysql";
1+
import { initOrm } from "#imports";
2+
import { defineConfig, type EntityManager, type MikroORM } from "@mikro-orm/mysql";
23

3-
export default defineNitroPlugin((nitro) => {
4-
nitro.hooks.callHook('mikroOrm:create', {
5-
config: defineConfig({
6-
host: '127.0.0.1',
7-
user: 'root',
8-
password: '',
9-
dbName: 'test',
10-
port: 3309,
11-
discovery: {
12-
warnWhenNoEntities: false,
13-
}
14-
})
15-
});
16-
17-
nitro.hooks.hook('mikroOrm:init', async (orm) => {
4+
export default defineNitroPlugin(async (_nitro) => {
5+
const orm = await initOrm<MikroORM>(defineConfig({
6+
host: '127.0.0.1',
7+
user: 'root',
8+
password: '',
9+
dbName: 'test',
10+
port: 3309,
11+
discovery: {
12+
warnWhenNoEntities: false,
13+
}
14+
}));
1815

19-
await orm.schema.ensureDatabase({create: true});
20-
const em = orm.em as EntityManager;
21-
await em.execute(`
22-
CREATE TABLE IF NOT EXISTS \`products\`
23-
(
24-
\`product_id\` INT UNSIGNED NOT NULL AUTO_INCREMENT,
25-
\`name\` VARCHAR(255) NOT NULL,
26-
PRIMARY KEY (\`product_id\`),
27-
UNIQUE INDEX \`name_UNIQUE\` (\`name\` ASC) VISIBLE
28-
)
29-
ENGINE = InnoDB
16+
await orm.schema.ensureDatabase({create: true});
17+
const em = orm.em as EntityManager;
18+
await em.execute(`
19+
CREATE TABLE IF NOT EXISTS \`products\`
20+
(
21+
\`product_id\` INT UNSIGNED NOT NULL AUTO_INCREMENT,
22+
\`name\` VARCHAR(255) NOT NULL,
23+
PRIMARY KEY (\`product_id\`),
24+
UNIQUE INDEX \`name_UNIQUE\` (\`name\` ASC) VISIBLE
25+
)
26+
ENGINE = InnoDB
3027
`);
31-
const productCount = (await em.execute<[{count: number}]>('SELECT COUNT(*) AS count FROM `products`'))[0].count;
32-
if (productCount === 0) {
33-
await em.execute(`
28+
const productCount = (await em.execute<[{count: number}]>('SELECT COUNT(*) AS count FROM `products`'))[0].count;
29+
if (productCount === 0) {
30+
await em.execute(`
3431
INSERT INTO products SET name = 'product 1'
3532
`); await em.execute(`
3633
INSERT INTO products SET name = 'product 2'
3734
`);
38-
}
39-
});
35+
}
4036
});

src/module.ts

Lines changed: 9 additions & 56 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,20 @@
1-
import {defineNuxtModule, createResolver, addServerPlugin, addServerImportsDir, logger, addImportsDir} from '@nuxt/kit';
2-
import {type defineConfig, type ForkOptions, type MikroORM, type EntityManager} from "@mikro-orm/core";
1+
import { defineNuxtModule, createResolver, addServerImportsDir, logger } from '@nuxt/kit';
2+
import { type ForkOptions, type EntityManager } from "@mikro-orm/core";
33
import { defu } from 'defu';
4-
import type {H3Event} from "h3";
4+
import type { EventHandlerRequest, H3Event } from "h3";
5+
6+
export type ForkOptionsFactory = (event: H3Event<EventHandlerRequest>, name: string) => ForkOptions|undefined;
57

68
export interface ModuleOptions {
79
/**
810
* Default fork options.
911
*
10-
* Used for every request.
11-
*
1212
* Key is the instance for which the fork options apply.
1313
* The default instance's key is "default".
14-
*/
15-
forkOptions?: Map<string, ForkOptions>;
16-
/**
17-
* Whether to enable fork options hook.
1814
*
19-
* If enabled, the default fork options are copied for each request,
20-
* and registered hook handlers for "mikroOrm:fork" are given the opportunity to modify those options
21-
* on a per-request basis by modifying the input args.
15+
* If an instance's options are left undefined, "{}" is used.
2216
*/
23-
enableForkHook?: boolean;
17+
forkOptions?: Map<string, ForkOptions>;
2418
}
2519

2620
declare module '@nuxt/schema' {
@@ -29,48 +23,9 @@ declare module '@nuxt/schema' {
2923
}
3024
}
3125

32-
export interface CreateHookArg {
33-
config: ReturnType<typeof defineConfig>;
34-
name?: string;
35-
}
36-
37-
declare module 'nitropack' {
38-
export interface NitroRuntimeHooks {
39-
/**
40-
* MikroORM create hook.
41-
*
42-
* User plugins must call this hook to create a new
43-
* instance with the given config.
44-
*
45-
* @param out
46-
*/
47-
'mikroOrm:create': (out: CreateHookArg) => void;
48-
49-
/**
50-
* MikroORM init hook.
51-
*
52-
* Called by this module after each ORM instance creation.
53-
*/
54-
'mikroOrm:init': (orm: MikroORM, name: string) => void;
55-
56-
/**
57-
* Called before a fork of MikroORM's EntityManager, at the request context.
58-
*
59-
* Only registered if the "enableForkHook" option is set to `true`.
60-
*
61-
* User plugins may register for this hook, to provide different fork options for each request.
62-
*
63-
* @param event Event at which the fork is happening.
64-
* @param forkOptions Options for the particular fork.
65-
* @param name Name of the instance being forked.
66-
*/
67-
'mikroOrm:fork': (event: H3Event, forkOptions: ForkOptions, name: string) => void;
68-
}
69-
}
70-
7126
declare module 'h3' {
7227
interface H3EventContext {
73-
em?: Map<string, EntityManager>;
28+
mikroOrmEntityManagers?: Map<string, EntityManager>;
7429
}
7530
}
7631

@@ -85,9 +40,7 @@ export default defineNuxtModule<ModuleOptions>({
8540
nuxt.options.runtimeConfig.mikroOrm = defu(nuxt.options.runtimeConfig.mikroOrm, options);
8641

8742
addServerImportsDir(resolve('./runtime/server/utils'));
88-
addServerPlugin(resolve('./runtime/server/plugins/mikro-orm'));
89-
addImportsDir(resolve('./runtime/composables'));
9043

91-
logger.info('MikroORM module is initialized');
44+
logger.debug('MikroORM module is initialized');
9245
},
9346
})

src/runtime/composables/em.ts

Lines changed: 0 additions & 15 deletions
This file was deleted.

src/runtime/server/plugins/mikro-orm.ts

Lines changed: 0 additions & 82 deletions
This file was deleted.

0 commit comments

Comments
 (0)