@meghjs/mcp 0.0.0-stage → 0.7.0

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.
Files changed (84) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +141 -2
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +37 -0
  5. package/dist/docs/advanced/caching.md +72 -0
  6. package/dist/docs/advanced/database.md +328 -0
  7. package/dist/docs/advanced/events.md +169 -0
  8. package/dist/docs/advanced/file-uploads.md +141 -0
  9. package/dist/docs/advanced/health.md +81 -0
  10. package/dist/docs/advanced/logging.md +96 -0
  11. package/dist/docs/advanced/mail.md +439 -0
  12. package/dist/docs/advanced/orm/migrations.md +210 -0
  13. package/dist/docs/advanced/orm/models.md +291 -0
  14. package/dist/docs/advanced/orm/queries.md +169 -0
  15. package/dist/docs/advanced/orm/query-builder.md +120 -0
  16. package/dist/docs/advanced/orm/relations.md +179 -0
  17. package/dist/docs/advanced/orm/seeding.md +129 -0
  18. package/dist/docs/advanced/orm.md +145 -0
  19. package/dist/docs/advanced/plugins.md +90 -0
  20. package/dist/docs/advanced/queue.md +217 -0
  21. package/dist/docs/advanced/scheduler.md +253 -0
  22. package/dist/docs/advanced/testing.md +257 -0
  23. package/dist/docs/advanced/views.md +335 -0
  24. package/dist/docs/ai/mcp.md +162 -0
  25. package/dist/docs/cli/basic.md +133 -0
  26. package/dist/docs/cli/database.md +112 -0
  27. package/dist/docs/cli/generators.md +605 -0
  28. package/dist/docs/cli/scaffold/auth.md +172 -0
  29. package/dist/docs/cli/scaffold/domains.md +224 -0
  30. package/dist/docs/cli/scaffold/index.md +77 -0
  31. package/dist/docs/cli/scaffold/rbac.md +118 -0
  32. package/dist/docs/cli/scaffold/templates.md +235 -0
  33. package/dist/docs/core-concept/authentication.md +162 -0
  34. package/dist/docs/core-concept/configuration.md +268 -0
  35. package/dist/docs/core-concept/controller.md +350 -0
  36. package/dist/docs/core-concept/dependency-injection.md +213 -0
  37. package/dist/docs/core-concept/error-handling.md +185 -0
  38. package/dist/docs/core-concept/middleware.md +143 -0
  39. package/dist/docs/core-concept/request-context.md +110 -0
  40. package/dist/docs/core-concept/validation.md +355 -0
  41. package/dist/docs/getting-started/application.md +233 -0
  42. package/dist/docs/getting-started/installation.md +166 -0
  43. package/dist/docs/getting-started/introduction.md +136 -0
  44. package/dist/docs/getting-started/upgrading-0.4.md +125 -0
  45. package/dist/docs/getting-started/upgrading-0.5.md +293 -0
  46. package/dist/docs/getting-started/upgrading-0.6.md +251 -0
  47. package/dist/docs/getting-started/upgrading-0.7.md +225 -0
  48. package/dist/docs/getting-started/upgrading-megh.md +91 -0
  49. package/dist/docs/getting-started/upgrading-next.md +12 -0
  50. package/dist/docs/getting-started/upgrading.md +137 -0
  51. package/dist/docs/getting-started/usage.md +194 -0
  52. package/dist/docs/index.md +58 -0
  53. package/dist/docs/microservices/openapi.md +387 -0
  54. package/dist/docs/microservices/websocket.md +165 -0
  55. package/dist/docs/production/deployment.md +256 -0
  56. package/dist/docs/production/security.md +307 -0
  57. package/dist/docs/reference/api.md +999 -0
  58. package/dist/docs/reference/faq.md +227 -0
  59. package/dist/docs/reference/versioning.md +105 -0
  60. package/dist/docs.d.ts +30 -0
  61. package/dist/docs.js +126 -0
  62. package/dist/index.d.ts +10 -0
  63. package/dist/index.js +22 -0
  64. package/dist/megh.d.ts +59 -0
  65. package/dist/megh.js +207 -0
  66. package/dist/prompts.d.ts +3 -0
  67. package/dist/prompts.js +47 -0
  68. package/dist/result.d.ts +18 -0
  69. package/dist/result.js +48 -0
  70. package/dist/server.d.ts +17 -0
  71. package/dist/server.js +40 -0
  72. package/dist/tools/context.d.ts +11 -0
  73. package/dist/tools/context.js +2 -0
  74. package/dist/tools/database.d.ts +8 -0
  75. package/dist/tools/database.js +58 -0
  76. package/dist/tools/docs.d.ts +3 -0
  77. package/dist/tools/docs.js +63 -0
  78. package/dist/tools/generate.d.ts +10 -0
  79. package/dist/tools/generate.js +177 -0
  80. package/dist/tools/project.d.ts +3 -0
  81. package/dist/tools/project.js +84 -0
  82. package/dist/version.d.ts +2 -0
  83. package/dist/version.js +10 -0
  84. package/package.json +58 -4
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Tareq Hossain
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 CHANGED
@@ -1,3 +1,142 @@
1
- # Temporary Holding Version
1
+ # Megh MCP Server
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A [Model Context Protocol](https://modelcontextprotocol.io) server that lets AI
4
+ assistants (Claude Code, Claude Desktop, Cursor, VS Code, ...) understand,
5
+ inspect and scaffold [Megh](https://github.com/meghjs/megh) applications.
6
+
7
+ It gives an assistant:
8
+
9
+ - **the Megh docs**, bundled with the server so they match its version, to
10
+ search and read instead of guessing at the API;
11
+ - **a view of your project**: dependencies, source files by kind, routes,
12
+ migration status, `megh doctor` checks and type errors;
13
+ - **the `megh` generators and scaffolds**, run the same way the CLI runs them;
14
+ - **migrations and seeders**, refused against a production project.
15
+
16
+ It wraps the `megh` CLI. It uses the `@meghjs/cli` installed in your project
17
+ when there is one, so the generated code matches your `@meghjs/core`, and
18
+ falls back to its own copy.
19
+
20
+ ## Setup
21
+
22
+ Claude Code, from your project directory:
23
+
24
+ ```sh
25
+ claude mcp add megh -- npx -y @meghjs/mcp
26
+ ```
27
+
28
+ Any client that reads an `mcpServers` config (Claude Desktop, Cursor, ...):
29
+
30
+ ```json
31
+ {
32
+ "mcpServers": {
33
+ "megh": {
34
+ "command": "npx",
35
+ "args": ["-y", "@meghjs/mcp", "/path/to/your/project"]
36
+ }
37
+ }
38
+ }
39
+ ```
40
+
41
+ VS Code (`.vscode/mcp.json` in your project):
42
+
43
+ ```json
44
+ {
45
+ "servers": {
46
+ "megh": {
47
+ "type": "stdio",
48
+ "command": "npx",
49
+ "args": ["-y", "@meghjs/mcp", "${workspaceFolder}"]
50
+ }
51
+ }
52
+ }
53
+ ```
54
+
55
+ To run a local build instead, build it from this repository
56
+ (`npm run build -w @meghjs/cli && npm run build -w @meghjs/mcp`) and use
57
+ `node /path/to/megh/packages/mcp/dist/bin.js` in place of `npx -y @meghjs/mcp`.
58
+
59
+ ### Options
60
+
61
+ ```
62
+ megh-mcp [project-dir] [--read-only]
63
+ ```
64
+
65
+ | Option | Environment | Description |
66
+ |--------|-------------|-------------|
67
+ | `project-dir` | `MEGH_PROJECT_ROOT` | The project tools work on by default. Defaults to the directory the server starts in. Every tool also takes an optional `cwd`. |
68
+ | `--read-only` | `MEGH_MCP_READ_ONLY=1` | Leave out every tool that writes files or changes the database, and the `megh-add-resource` prompt. |
69
+ | | `MEGH_DOCS_DIR` | Serve docs from this folder instead of the bundled ones. |
70
+
71
+ ## Tools
72
+
73
+ ### Project (read-only)
74
+
75
+ | Tool | What it does |
76
+ |------|--------------|
77
+ | `megh_project_info` | Project root, `@meghjs/*` dependencies (declared and installed), scripts, `megh` settings, whether it runs in production |
78
+ | `megh_project_structure` | Source files grouped by kind (controllers, services, models, dtos, migrations, seeders, ...), with counts and the entry file |
79
+ | `megh_doctor` | The `megh doctor` checks as JSON: Node.js, `@meghjs/core`, `reflect-metadata`, decorator settings |
80
+ | `megh_list_routes` | `megh route:list --json`. `static: true` scans the decorators without running code |
81
+ | `megh_list_templates` | `megh template:list [domain] --json` |
82
+ | `megh_typecheck` | The project's `tsc --noEmit`, returning the errors |
83
+ | `megh_migrate_status` | `megh migrate:status --json` |
84
+
85
+ ### Docs (read-only)
86
+
87
+ | Tool | What it does |
88
+ |------|--------------|
89
+ | `megh_search_docs` | Search the Megh docs; returns the best-matching pages with snippets |
90
+ | `megh_read_doc` | Read a page as markdown, e.g. `core-concept/controller`; with no page, list them all |
91
+
92
+ ### Code generation
93
+
94
+ | Tool | What it does |
95
+ |------|--------------|
96
+ | `megh_make` | `megh make:<kind> <name>` for model, controller, service, resource, dto, config, middleware, mail, event, listener, queue, worker, task, migration, seeder, factory. Takes `force`, `table`, `create`, `template`, `fields`, `factory` |
97
+ | `megh_sync_model` | `megh sync:model`: update a model after an alter-table migration. `dryRun` shows the changes first |
98
+ | `megh_scaffold_domain` | `megh scaffold:domain`: the tables (and models or resources) of a domain's templates |
99
+ | `megh_scaffold_auth` | `megh scaffold:auth`: sign-up and sign-in with JWT, API keys or both, optionally with roles |
100
+ | `megh_scaffold_rbac` | `megh scaffold:rbac`: roles and permissions for an app that already has users |
101
+ | `megh_build` | `megh build`: compile to the output folder and copy assets |
102
+
103
+ The generators never prompt and leave existing files alone unless `force` is
104
+ set.
105
+
106
+ ### Database
107
+
108
+ | Tool | What it does |
109
+ |------|--------------|
110
+ | `megh_migrate` | Run the pending migrations, optionally followed by the seeders |
111
+ | `megh_migrate_rollback` | Undo the last migration, or the last `step` (marked destructive) |
112
+ | `megh_db_seed` | Run the seeders, or one `seeder` |
113
+
114
+ These refuse to run when `NODE_ENV` is `production`, from the server's
115
+ environment or the project's `.env`. `migrate:reset` and `migrate:refresh` are
116
+ not exposed because they drop every table. Run those yourself.
117
+
118
+ ## Resources
119
+
120
+ | URI | Contents |
121
+ |-----|----------|
122
+ | `megh://docs/{page}` | A docs page as markdown, e.g. `megh://docs/advanced/orm` (each page is listed) |
123
+ | `megh://project/info` | The server's project, as `megh_project_info` returns it |
124
+ | `megh://project/structure` | The server's project files, as `megh_project_structure` returns them |
125
+
126
+ ## Prompts
127
+
128
+ | Prompt | What it does |
129
+ |--------|--------------|
130
+ | `megh-review-project` | Check the setup, routes, structure and type errors, and point out problems |
131
+ | `megh-explain` | Explain a Megh feature (`topic`) from the docs, with an example that fits the project |
132
+ | `megh-add-resource` | Add a table, model and CRUD API for `name` (with optional `fields`), migrate, and check it compiles. Not offered in read-only mode |
133
+
134
+ ## Use it as a library
135
+
136
+ ```ts
137
+ import { createServer } from "@meghjs/mcp";
138
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
139
+
140
+ const server = createServer({ projectRoot: "/path/to/app", readOnly: true });
141
+ await server.connect(new StdioServerTransport());
142
+ ```
package/dist/bin.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/bin.js ADDED
@@ -0,0 +1,37 @@
1
+ #!/usr/bin/env node
2
+ "use strict";
3
+ Object.defineProperty(exports, "__esModule", { value: true });
4
+ const stdio_js_1 = require("@modelcontextprotocol/sdk/server/stdio.js");
5
+ const server_1 = require("./server");
6
+ const version_1 = require("./version");
7
+ const USAGE = `Usage: megh-mcp [project-dir] [--read-only]
8
+
9
+ Serve the Megh tools over stdio for an MCP client.
10
+
11
+ project-dir The Megh project (default: MEGH_PROJECT_ROOT, else the current directory)
12
+ --read-only Leave out the tools that write files or change the database
13
+ (or set MEGH_MCP_READ_ONLY=1)
14
+ -v, --version Print the version
15
+ -h, --help Show this help`;
16
+ /** stdout carries the protocol, so anything else must go to stderr. */
17
+ async function main() {
18
+ const args = process.argv.slice(2);
19
+ if (args.includes("-h") || args.includes("--help"))
20
+ return void console.error(USAGE);
21
+ if (args.includes("-v") || args.includes("--version"))
22
+ return void console.error(version_1.version);
23
+ const unknown = args.find((a) => a.startsWith("-") && a !== "--read-only");
24
+ if (unknown) {
25
+ console.error(`Unknown option ${unknown}\n\n${USAGE}`);
26
+ process.exit(1);
27
+ }
28
+ const projectRoot = args.find((a) => !a.startsWith("-")) ?? process.env.MEGH_PROJECT_ROOT;
29
+ const readOnly = args.includes("--read-only") || process.env.MEGH_MCP_READ_ONLY === "1";
30
+ const server = (0, server_1.createServer)({ projectRoot, version: version_1.version, readOnly });
31
+ await server.connect(new stdio_js_1.StdioServerTransport());
32
+ console.error(`megh-mcp ${version_1.version} ready (project: ${projectRoot ?? process.cwd()}${readOnly ? ", read-only" : ""})`);
33
+ }
34
+ main().catch((err) => {
35
+ console.error(err);
36
+ process.exit(1);
37
+ });
@@ -0,0 +1,72 @@
1
+ ---
2
+ title: Caching
3
+ description: In-memory and Redis caching with tags.
4
+ ---
5
+
6
+ # Caching
7
+
8
+ Enable the cache on the app. It is in-memory by default:
9
+
10
+ ```ts [app.ts]
11
+ app.useCache({ provider: 'memory' });
12
+ ```
13
+
14
+ For Redis, install `ioredis` and pass its options:
15
+
16
+ ```ts
17
+ app.useCache({
18
+ provider: 'redis',
19
+ redisOptions: { host: '127.0.0.1', port: 6379 },
20
+ });
21
+ ```
22
+
23
+ ## Using the cache
24
+
25
+ Inject `CacheManager`. `set` takes a key, a value, a TTL in seconds, and
26
+ optional tags:
27
+
28
+ ```ts [services/users.service.ts]
29
+ import { AppService, CacheManager } from '@meghjs/core';
30
+
31
+ @AppService
32
+ export class UsersService {
33
+ constructor(private readonly cache: CacheManager) {}
34
+
35
+ async findAll() {
36
+ const cached = await this.cache.get<User[]>('users:all');
37
+ if (cached) return cached;
38
+
39
+ const users = await this.repo.find();
40
+ await this.cache.set('users:all', users, 3600, ['users']);
41
+ return users;
42
+ }
43
+
44
+ async update(user: User) {
45
+ await this.repo.save(user);
46
+ await this.cache.invalidateTags('users'); // drops every key tagged 'users'
47
+ }
48
+ }
49
+ ```
50
+
51
+ ## Expiry
52
+
53
+ - A TTL of `0` or less means the entry never expires.
54
+ - The memory store drops expired entries when they are read, and in a
55
+ background sweep every 60 seconds. The sweep does not keep the process alive.
56
+ - The memory store has no size limit, so give large or numerous entries a TTL.
57
+ - In Redis, tag sets expire no earlier than the longest-lived key they track.
58
+
59
+ ## Instances
60
+
61
+ The `CacheManager` registered by `useCache` is a singleton shared through
62
+ dependency injection. `new CacheManager(options)` creates an independent store,
63
+ which is useful in tests:
64
+
65
+ ```ts
66
+ const cache = new CacheManager({ provider: 'memory', sweepIntervalMs: 1000 });
67
+ cache.sweep(); // remove expired entries now; returns how many
68
+ await cache.close(); // stop the sweep timer and release resources
69
+ ```
70
+
71
+ Call `await CacheManager.close()` on shutdown to close every instance,
72
+ including the Redis client.
@@ -0,0 +1,328 @@
1
+ ---
2
+ title: TypeORM and Knex
3
+ description: Using TypeORM or Knex through @meghjs/data, as an alternative to MeghORM.
4
+ ---
5
+
6
+ # TypeORM and Knex
7
+
8
+ ::: tip Built-in models
9
+ `@meghjs/core` also has its own type-safe models and migrations, built on
10
+ Kysely, with no extra Megh package. See [MeghORM](/advanced/orm).
11
+ :::
12
+
13
+ The `@meghjs/data` package adds two database integrations: **TypeORM** for an
14
+ entity/repository model, and **Knex** for a query builder. Install it with the
15
+ library you use and its driver. It needs `@meghjs/core` 0.4 or later.
16
+
17
+ ::: code-group
18
+ ```sh [TypeORM]
19
+ npm i @meghjs/data typeorm pg
20
+ ```
21
+ ```sh [Knex]
22
+ npm i @meghjs/data knex pg
23
+ ```
24
+ :::
25
+
26
+ `@meghjs/data` is a [plugin](/advanced/plugins): once it is installed,
27
+ `app.useTypeORM()` and `app.useKnex()` are available, with no import needed. Projects
28
+ created with `megh new` load its types through the generated
29
+ `megh-env.d.ts`. In other projects, add that file yourself and include it in
30
+ `tsconfig.json`:
31
+
32
+ ```ts [megh-env.d.ts]
33
+ /// <reference types="@meghjs/data" />
34
+ ```
35
+
36
+ ```json [tsconfig.json]
37
+ {
38
+ "include": ["megh-env.d.ts", "src/**/*"]
39
+ }
40
+ ```
41
+
42
+ Both methods connect before they resolve, so await them before `app.run()`.
43
+ The connection is closed when the app shuts down.
44
+
45
+ ## TypeORM
46
+
47
+ Register the datasource on the app with `useTypeORM`. It is asynchronous, so
48
+ await it before the app runs.
49
+
50
+ ```ts [app.ts]
51
+ import { Megh } from '@meghjs/core';
52
+ import { User } from './models/user';
53
+ import { UsersController } from './controllers/users.controller';
54
+
55
+ const app = Megh.createApplication();
56
+
57
+ export async function setup() {
58
+ await app.useTypeORM({
59
+ type: 'postgres',
60
+ host: 'localhost',
61
+ port: 5432,
62
+ username: 'postgres',
63
+ password: 'postgres',
64
+ database: 'myapi',
65
+ entities: [User],
66
+ synchronize: true, // development only
67
+ });
68
+
69
+ app.useControllers([UsersController]);
70
+ return app;
71
+ }
72
+
73
+ export default app;
74
+ ```
75
+
76
+ ```ts [serve.ts]
77
+ import { Environment, inject } from '@meghjs/core';
78
+ import app, { setup } from './app';
79
+
80
+ async function serve() {
81
+ await setup();
82
+ const env = inject(Environment);
83
+ await app.run(Number(env.get('PORT')) || 4000);
84
+ }
85
+
86
+ serve();
87
+ ```
88
+
89
+ ::: info
90
+ The project generated by `megh new` compiles to CommonJS, where top-level
91
+ `await` is not available. Wrap async setup in a function and await it from your
92
+ entry point, as above.
93
+ :::
94
+
95
+ ### Defining an entity
96
+
97
+ ```ts [models/user.ts]
98
+ import { Entity, PrimaryGeneratedColumn, Column, CreateDateColumn } from 'typeorm';
99
+
100
+ @Entity({ name: 'user' })
101
+ export class User {
102
+ @PrimaryGeneratedColumn()
103
+ id: number;
104
+
105
+ @Column()
106
+ name: string;
107
+
108
+ @CreateDateColumn()
109
+ createdAt: Date;
110
+ }
111
+ ```
112
+
113
+ Generate one with the CLI:
114
+
115
+ ```sh
116
+ npx megh make:model user --typeorm
117
+ ```
118
+
119
+ ### Injecting a repository
120
+
121
+ Use `@InjectRepository` to receive a TypeORM `Repository` in any service or
122
+ controller. It also has a `paginate()` method, so type it as
123
+ `PaginatedRepository`:
124
+
125
+ ```ts [services/user.service.ts]
126
+ import { AppService } from '@meghjs/core';
127
+ import { InjectRepository, PaginatedRepository } from '@meghjs/data';
128
+ import { User } from '../models/user';
129
+
130
+ @AppService
131
+ export class UserService {
132
+ constructor(
133
+ @InjectRepository(User)
134
+ private readonly userRepository: PaginatedRepository<User>,
135
+ ) {}
136
+
137
+ findAll() {
138
+ return this.userRepository.find();
139
+ }
140
+
141
+ page(page: number) {
142
+ return this.userRepository.paginate({ page, perPage: 20 });
143
+ }
144
+
145
+ findByPk(id: number) {
146
+ return this.userRepository.findOneBy({ id });
147
+ }
148
+
149
+ create(body: Partial<User>) {
150
+ const user = this.userRepository.create(body);
151
+ return this.userRepository.save(user);
152
+ }
153
+ }
154
+ ```
155
+
156
+ ### Using a config class
157
+
158
+ Instead of an inline object, `useTypeORM` also accepts an `@AppConfig` class.
159
+ This keeps credentials in one place and gives access to the environment:
160
+
161
+ ::: code-group
162
+ ```ts [config/database.config.ts]
163
+ import { AppConfig, MeghConfig, Environment } from '@meghjs/core';
164
+ import { DataSourceOptions } from 'typeorm';
165
+ import { User } from '../models/user';
166
+
167
+ @AppConfig
168
+ export class DatabaseConfig extends MeghConfig<DataSourceOptions> {
169
+ config(env: Environment): DataSourceOptions {
170
+ return {
171
+ type: 'postgres',
172
+ url: env.get<string>('DATABASE_URL'),
173
+ entities: [User],
174
+ };
175
+ }
176
+ }
177
+ ```
178
+
179
+ ```ts [app.ts]
180
+ import { Megh } from '@meghjs/core';
181
+ import { DatabaseConfig } from './config/database.config';
182
+
183
+ const app = Megh.createApplication();
184
+
185
+ export async function setup() {
186
+ await app.useTypeORM(DatabaseConfig);
187
+ return app;
188
+ }
189
+
190
+ export default app;
191
+ ```
192
+ :::
193
+
194
+ ### Custom repositories
195
+
196
+ Extend `MeghRepository` to keep queries in one class, with pagination and
197
+ transactions built in. Query operators (`Like`, `ILike`, `In`, `Not`, `Between`,
198
+ `LessThan`, `MoreThan`, `IsNull`, `Any`, `Raw`, `Equal`, `ArrayContains`) are
199
+ exported from `@meghjs/data`.
200
+
201
+ ```ts [repositories/user.repository.ts]
202
+ import { MeghRepository, Repository, Like } from '@meghjs/data';
203
+ import { User } from '../models/user';
204
+ import { AuditService } from '../services/audit.service';
205
+
206
+ @Repository(User)
207
+ export class UserRepository extends MeghRepository<User> {
208
+ constructor(private readonly audit: AuditService) {
209
+ super();
210
+ }
211
+
212
+ search(term: string, page = 1) {
213
+ return this.paginate(
214
+ { where: { name: Like(`%${term}%`) } }, // TypeORM find options
215
+ { page, perPage: 20 },
216
+ );
217
+ }
218
+
219
+ rename(id: number, name: string) {
220
+ return this.transaction(async (tx) => {
221
+ await tx.update({ id }, { name });
222
+ await this.audit.log('rename', id);
223
+ });
224
+ }
225
+ }
226
+ ```
227
+
228
+ ::: warning
229
+ In 0.3.0, a `@Repository` class must declare a constructor that calls
230
+ `super()`, even with no dependencies. Without one, resolving it through
231
+ dependency injection fails on the first query.
232
+ :::
233
+
234
+ - `transaction(work)` joins a transaction that is already active instead of
235
+ opening a nested one. The `tx` repository keeps your injected dependencies.
236
+ - `withManager(manager)` returns a copy bound to another `EntityManager`.
237
+
238
+ ## Knex
239
+
240
+ Register the connection with `useKnex`, which takes a Knex config or an
241
+ `@AppConfig` class just like `useTypeORM`:
242
+
243
+ ```ts [app.ts]
244
+ import { Megh } from '@meghjs/core';
245
+
246
+ const app = Megh.createApplication();
247
+
248
+ export async function setup() {
249
+ await app.useKnex({
250
+ client: 'pg',
251
+ connection: process.env.DATABASE_URL,
252
+ });
253
+ return app;
254
+ }
255
+
256
+ export default app;
257
+ ```
258
+
259
+ Call `setup()` from `serve.ts` before `app.run()`, as in the TypeORM example.
260
+
261
+ Inject `KnexDB` to reach the query builder through its `client` property:
262
+
263
+ ```ts [services/report.service.ts]
264
+ import { AppService } from '@meghjs/core';
265
+ import { KnexDB } from '@meghjs/data';
266
+
267
+ @AppService
268
+ export class ReportService {
269
+ constructor(private readonly db: KnexDB) {}
270
+
271
+ activeUsers() {
272
+ return this.db.client('user').where({ active: true }).select('*');
273
+ }
274
+
275
+ page(page: number) {
276
+ return this.db.paginate(this.db.client('user').orderBy('id'), { page, perPage: 20 });
277
+ }
278
+ }
279
+ ```
280
+
281
+ `KnexDB` throws if it is resolved before `useKnex` has run, so always register
282
+ the connection during app setup. `paginateKnex(query, { page, perPage })` does
283
+ the same as `db.paginate` without injecting `KnexDB`.
284
+
285
+ ## Pagination
286
+
287
+ Every paginator takes `{ page, perPage }` and returns the same shape:
288
+
289
+ | Source | Call |
290
+ |--------|------|
291
+ | `@InjectRepository` | `repo.paginate({ page, perPage })` |
292
+ | `MeghRepository` | `this.paginate(findOptions, { page, perPage })` |
293
+ | `KnexDB` | `db.paginate(query, { page, perPage })` |
294
+ | `Collection` | `collection.paginate({ page, perPage })` |
295
+
296
+ ```json
297
+ {
298
+ "data": [ ... ],
299
+ "meta": { "total": 57, "page": 2, "perPage": 20, "lastPage": 3, "next": 3, "prev": 1 }
300
+ }
301
+ ```
302
+
303
+ `page` defaults to 1 and `perPage` to 10. `next` and `prev` are page numbers.
304
+ They are `null` at either end. The `Paginated<T>` and `PageRequest` types are
305
+ exported.
306
+
307
+ ## Without a database
308
+
309
+ For prototypes and tests, `Collection` gives the same shape of API over an
310
+ in-memory array — see [Controller](/core-concept/controller) for an example.
311
+
312
+ ## Troubleshooting
313
+
314
+ | Symptom | Fix |
315
+ |---------|-----|
316
+ | TypeScript: `Property 'useKnex' does not exist` (or `useTypeORM`) | Add `megh-env.d.ts` and include it in `tsconfig.json`, as shown above. Importing anything from `@meghjs/data` in your code has the same effect. |
317
+ | Runtime: `app.useKnex is not a function` | List `@meghjs/data` in `package.json` dependencies, use `@meghjs/core` 0.4 or later, and start the app from the project root: plugins are found from the `package.json` in the current directory. A bundled app has no `package.json` at runtime; pass the plugin explicitly (below). |
318
+ | `pg is required but not installed` | Install the driver named in `client` (or `type` for TypeORM). |
319
+ | `Knex is not initialized. Call useKnex first.` | A service using `KnexDB` was created before `useKnex` finished. Await `setup()` before `app.run()`. |
320
+
321
+ To register the plugin yourself, for a bundled app or to turn off discovery:
322
+
323
+ ```ts
324
+ import { Megh } from '@meghjs/core';
325
+ import { dataPlugin } from '@meghjs/data';
326
+
327
+ const app = Megh.createApplication({ plugins: [dataPlugin] });
328
+ ```