@arkormx/plugin-clear-router 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 h3ravel
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,95 @@
1
+ # @arkormx/plugin-clear-router
2
+
3
+ Clear Router plugin for resolving Arkormx models from route parameters.
4
+
5
+ ```ts
6
+ import { Router } from 'clear-router/express'
7
+ import { clearRouterPlugin } from '@arkormx/plugin-clear-router'
8
+
9
+ Router.use(clearRouterPlugin)
10
+ ```
11
+
12
+ ## What it does
13
+
14
+ When a controller action is decorated with `@Bind()`, the plugin checks each bound argument. If the argument type extends `arkormx`'s `Model`, the plugin resolves the matching route parameter and passes the hydrated model instance to the controller.
15
+
16
+ ```ts
17
+ import { Bind } from 'clear-router/decorators'
18
+ import { Controller } from 'clear-router'
19
+ import { User } from './models/User'
20
+
21
+ class UserController extends Controller {
22
+ @Bind()
23
+ async show (user: User) {
24
+ return {
25
+ data: user,
26
+ }
27
+ }
28
+ }
29
+
30
+ Router.get('/users/:user', [UserController, 'show'])
31
+ ```
32
+
33
+ For `/users/1`, the `user` argument is resolved with:
34
+
35
+ ```ts
36
+ await User.query().find('1', 'id')
37
+ ```
38
+
39
+ Non-model arguments continue to resolve through Clear Router's container.
40
+
41
+ ## Route Parameter Names
42
+
43
+ The plugin derives the route parameter name from the model class name:
44
+
45
+ | Model class | Route parameter |
46
+ | --- | --- |
47
+ | `User` | `:user` or `{user}` |
48
+ | `Profile` | `:profile` or `{profile}` |
49
+ | `UserModel` | `:user` or `{user}` |
50
+
51
+ Both Clear Router parameter styles are supported:
52
+
53
+ ```ts
54
+ Router.get('/users/:user', [UserController, 'show'])
55
+ Router.get('/users/{user}', [UserController, 'show'])
56
+ ```
57
+
58
+ ## Custom Binding Fields
59
+
60
+ Use `:name:field` or `{name:field}` to resolve by a non-primary column:
61
+
62
+ ```ts
63
+ Router.get('/users/{user:email}', [UserController, 'show'])
64
+ ```
65
+
66
+ For `/users/jane@example.com`, the plugin runs:
67
+
68
+ ```ts
69
+ await User.query().find('jane@example.com', 'email')
70
+ ```
71
+
72
+ ## Custom Model Resolution
73
+
74
+ Models can override the default lookup by defining `resolveRouteBinding`:
75
+
76
+ ```ts
77
+ import { Model } from 'arkormx'
78
+
79
+ export class User extends Model {
80
+ async resolveRouteBinding (value: unknown, field = 'id') {
81
+ return await User.query()
82
+ .whereKey(field as 'id', value as never)
83
+ .firstOrFail()
84
+ }
85
+ }
86
+ ```
87
+
88
+ The method receives the raw route value and the binding field, if one was provided in the route.
89
+
90
+ ## Development
91
+
92
+ ```sh
93
+ pnpm test
94
+ pnpm build
95
+ ```
package/dist/index.cjs ADDED
@@ -0,0 +1,88 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ let clear_router_decorators_setup = require("clear-router/decorators/setup");
3
+ let arkormx = require("arkormx");
4
+ let clear_router_core = require("clear-router/core");
5
+
6
+ //#region src/helpers.ts
7
+ async function resolveRouteBinding(modelClass, value, field) {
8
+ const instance = new modelClass();
9
+ if (typeof instance.resolveRouteBinding === "function") return await instance.resolveRouteBinding(value, field);
10
+ const resolvedField = field ?? modelClass.getPrimaryKey();
11
+ return await modelClass.query().where({ [resolvedField]: value }).firstOrFail();
12
+ }
13
+ const isModel = (cls) => {
14
+ return typeof cls === "function" && cls.prototype instanceof arkormx.Model;
15
+ };
16
+ const getRouteBindingName = (modelClass) => {
17
+ return modelClass.name.replace(/Model$/, "").replace(/^[A-Z]/, (letter) => letter.toLowerCase());
18
+ };
19
+
20
+ //#endregion
21
+ //#region src/RouteBindingParamExtractor.ts
22
+ var RouteBindingParamExtractor = class {
23
+ static extract(routePath, requestPath, params, bindingName) {
24
+ const routeSegments = this.normalizePath(routePath);
25
+ const requestSegments = this.normalizePath(requestPath);
26
+ const positionalParams = routeSegments.map((segment, index) => {
27
+ const match = this.getRouteParamMatch(segment);
28
+ if (!match) return;
29
+ return {
30
+ name: match.name,
31
+ field: match.field,
32
+ value: requestSegments[index]
33
+ };
34
+ }).filter((param) => {
35
+ return Boolean(param);
36
+ });
37
+ const matched = positionalParams.find((param) => {
38
+ return param?.name === bindingName;
39
+ });
40
+ if (matched) return matched;
41
+ const fallbackValues = Object.values(params);
42
+ const bindingIndex = positionalParams.findIndex((param) => {
43
+ return param?.name === bindingName;
44
+ });
45
+ if (bindingIndex >= 0) return {
46
+ name: bindingName,
47
+ value: fallbackValues[bindingIndex]
48
+ };
49
+ }
50
+ static normalizePath(path) {
51
+ return path.split("/").filter(Boolean);
52
+ }
53
+ static getRouteParamMatch(segment) {
54
+ const colonMatch = segment.match(/^:([^/?#:]+)(?::([^/?#]+))?$/);
55
+ if (colonMatch) return {
56
+ name: colonMatch[1],
57
+ field: colonMatch[2]
58
+ };
59
+ const braceMatch = segment.match(/^\{([^}:]+)(?::([^}]+))?\}$/);
60
+ if (braceMatch) return {
61
+ name: braceMatch[1],
62
+ field: braceMatch[2]
63
+ };
64
+ }
65
+ };
66
+
67
+ //#endregion
68
+ //#region src/index.ts
69
+ const clearRouterPlugin = (0, clear_router_core.definePlugin)({
70
+ name: "plugin-clear-router",
71
+ async setup({ resolveArguments, configureDefaults }) {
72
+ configureDefaults({ container: {
73
+ enabled: true,
74
+ autoDiscover: true
75
+ } });
76
+ resolveArguments(async ({ request, tokens }) => {
77
+ return await Promise.all(tokens.map(async (token) => {
78
+ if (!isModel(token)) return await clear_router_decorators_setup.Container.resolve(token, request.ctx, true);
79
+ const binding = RouteBindingParamExtractor.extract(request.route.path, request.path, request.params, getRouteBindingName(token));
80
+ if (!binding) return await clear_router_decorators_setup.Container.resolve(token, request.ctx, true);
81
+ return await resolveRouteBinding(token, binding.value, binding.field);
82
+ }));
83
+ });
84
+ }
85
+ });
86
+
87
+ //#endregion
88
+ exports.clearRouterPlugin = clearRouterPlugin;
@@ -0,0 +1,16 @@
1
+ import * as clear_router_core0 from "clear-router/core";
2
+
3
+ //#region src/types.d.ts
4
+ interface Options {
5
+ /**
6
+ * Absolute path or path relative to cwd where models are stored
7
+ *
8
+ * @default arkormx default paths.models config
9
+ */
10
+ modelsPath?: string;
11
+ }
12
+ //#endregion
13
+ //#region src/index.d.ts
14
+ declare const clearRouterPlugin: clear_router_core0.ClearRouterPlugin<Options>;
15
+ //#endregion
16
+ export { clearRouterPlugin };
@@ -0,0 +1,17 @@
1
+ import { Model } from "arkormx";
2
+ import * as clear_router_core0 from "clear-router/core";
3
+
4
+ //#region src/types.d.ts
5
+ interface Options {
6
+ /**
7
+ * Absolute path or path relative to cwd where models are stored
8
+ *
9
+ * @default arkormx default paths.models config
10
+ */
11
+ modelsPath?: string;
12
+ }
13
+ //#endregion
14
+ //#region src/index.d.ts
15
+ declare const clearRouterPlugin: clear_router_core0.ClearRouterPlugin<Options>;
16
+ //#endregion
17
+ export { clearRouterPlugin };
package/dist/index.mjs ADDED
@@ -0,0 +1,87 @@
1
+ import { Container } from "clear-router/decorators/setup";
2
+ import { Model } from "arkormx";
3
+ import { definePlugin } from "clear-router/core";
4
+
5
+ //#region src/helpers.ts
6
+ async function resolveRouteBinding(modelClass, value, field) {
7
+ const instance = new modelClass();
8
+ if (typeof instance.resolveRouteBinding === "function") return await instance.resolveRouteBinding(value, field);
9
+ const resolvedField = field ?? modelClass.getPrimaryKey();
10
+ return await modelClass.query().where({ [resolvedField]: value }).firstOrFail();
11
+ }
12
+ const isModel = (cls) => {
13
+ return typeof cls === "function" && cls.prototype instanceof Model;
14
+ };
15
+ const getRouteBindingName = (modelClass) => {
16
+ return modelClass.name.replace(/Model$/, "").replace(/^[A-Z]/, (letter) => letter.toLowerCase());
17
+ };
18
+
19
+ //#endregion
20
+ //#region src/RouteBindingParamExtractor.ts
21
+ var RouteBindingParamExtractor = class {
22
+ static extract(routePath, requestPath, params, bindingName) {
23
+ const routeSegments = this.normalizePath(routePath);
24
+ const requestSegments = this.normalizePath(requestPath);
25
+ const positionalParams = routeSegments.map((segment, index) => {
26
+ const match = this.getRouteParamMatch(segment);
27
+ if (!match) return;
28
+ return {
29
+ name: match.name,
30
+ field: match.field,
31
+ value: requestSegments[index]
32
+ };
33
+ }).filter((param) => {
34
+ return Boolean(param);
35
+ });
36
+ const matched = positionalParams.find((param) => {
37
+ return param?.name === bindingName;
38
+ });
39
+ if (matched) return matched;
40
+ const fallbackValues = Object.values(params);
41
+ const bindingIndex = positionalParams.findIndex((param) => {
42
+ return param?.name === bindingName;
43
+ });
44
+ if (bindingIndex >= 0) return {
45
+ name: bindingName,
46
+ value: fallbackValues[bindingIndex]
47
+ };
48
+ }
49
+ static normalizePath(path) {
50
+ return path.split("/").filter(Boolean);
51
+ }
52
+ static getRouteParamMatch(segment) {
53
+ const colonMatch = segment.match(/^:([^/?#:]+)(?::([^/?#]+))?$/);
54
+ if (colonMatch) return {
55
+ name: colonMatch[1],
56
+ field: colonMatch[2]
57
+ };
58
+ const braceMatch = segment.match(/^\{([^}:]+)(?::([^}]+))?\}$/);
59
+ if (braceMatch) return {
60
+ name: braceMatch[1],
61
+ field: braceMatch[2]
62
+ };
63
+ }
64
+ };
65
+
66
+ //#endregion
67
+ //#region src/index.ts
68
+ const clearRouterPlugin = definePlugin({
69
+ name: "plugin-clear-router",
70
+ async setup({ resolveArguments, configureDefaults }) {
71
+ configureDefaults({ container: {
72
+ enabled: true,
73
+ autoDiscover: true
74
+ } });
75
+ resolveArguments(async ({ request, tokens }) => {
76
+ return await Promise.all(tokens.map(async (token) => {
77
+ if (!isModel(token)) return await Container.resolve(token, request.ctx, true);
78
+ const binding = RouteBindingParamExtractor.extract(request.route.path, request.path, request.params, getRouteBindingName(token));
79
+ if (!binding) return await Container.resolve(token, request.ctx, true);
80
+ return await resolveRouteBinding(token, binding.value, binding.field);
81
+ }));
82
+ });
83
+ }
84
+ });
85
+
86
+ //#endregion
87
+ export { clearRouterPlugin };
package/package.json ADDED
@@ -0,0 +1,55 @@
1
+ {
2
+ "name": "@arkormx/plugin-clear-router",
3
+ "version": "0.1.0",
4
+ "description": "Clear Router plugin for resolving Arkormx models from route parameters.",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "keywords": [
9
+ "resora",
10
+ "clear-router",
11
+ "express",
12
+ "h3",
13
+ "plugin",
14
+ "typescript"
15
+ ],
16
+ "license": "MIT",
17
+ "type": "module",
18
+ "main": "./dist/index.cjs",
19
+ "module": "./dist/index.mjs",
20
+ "types": "./dist/index.d.cts",
21
+ "exports": {
22
+ ".": {
23
+ "import": "./dist/index.mjs",
24
+ "require": "./dist/index.cjs"
25
+ },
26
+ "./package.json": "./package.json"
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "README.md"
31
+ ],
32
+ "dependencies": {
33
+ "reflect-metadata": "^0.2.2",
34
+ "arkormx": "2.0.7"
35
+ },
36
+ "peerDependencies": {
37
+ "clear-router": "^2.6.0"
38
+ },
39
+ "peerDependenciesMeta": {
40
+ "clear-router": {
41
+ "optional": false
42
+ }
43
+ },
44
+ "devDependencies": {
45
+ "clear-router": "^2.6.0",
46
+ "express": "^5.2.1",
47
+ "parasito": "^0.1.6"
48
+ },
49
+ "scripts": {
50
+ "test": "vitest run tests/*.spec.ts",
51
+ "build": "tsdown",
52
+ "lint": "eslint src tests --ext .ts",
53
+ "version:patch": "pnpm version patch"
54
+ }
55
+ }