@kadirgun/lucid-bravo 0.0.1

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.md ADDED
@@ -0,0 +1,9 @@
1
+ # The MIT License
2
+
3
+ Copyright (c) 2023
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the 'Software'), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
+
7
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
+
9
+ THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,98 @@
1
+ # Lucid Bravo
2
+
3
+ Lucid Bravo is a fluent query builder for AdonisJS Lucid models. It helps you keep filtering, sorting, relation preloading, and pagination in one place instead of spreading that logic across controllers.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @kadirgun/lucid-bravo
9
+ ```
10
+
11
+ ## Configure
12
+
13
+ Run the package configure command once in your AdonisJS app:
14
+
15
+ ```bash
16
+ node ace configure @kadirgun/lucid-bravo
17
+ ```
18
+
19
+ This registers the package command so you can generate new Bravo classes with the scaffold command.
20
+
21
+ ## Generate a Bravo class
22
+
23
+ ```bash
24
+ node ace make:bravo User
25
+ ```
26
+
27
+ The command creates a file like `app/bravos/user_bravo.ts` with a ready-to-edit class that extends `LucidBravo`.
28
+
29
+ ## Basic usage
30
+
31
+ Create a Bravo class for each model and define the allowed sort fields, preload relations, and model-specific filters. The generated scaffold already includes the base-class import, so the example below shows only the parts you normally customize.
32
+
33
+ ```ts
34
+ export default class UserBravo extends LucidBravo<typeof User> {
35
+ protected defaultLimit = 20
36
+ protected defaultSort = { field: 'name', order: 'asc' as const }
37
+
38
+ public override getSortable(): string[] {
39
+ return ['id', 'name']
40
+ }
41
+
42
+ public override getAllowedIncludes(): string[] {
43
+ return ['posts']
44
+ }
45
+
46
+ public async name(value: string) {
47
+ this.$query.where('name', value)
48
+ }
49
+ }
50
+ ```
51
+
52
+ Use the class in a controller or service with the query builder and request params:
53
+
54
+ ```ts
55
+ const bravo = new UserBravo(User.query(), {
56
+ sort: { field: 'name', order: 'asc' },
57
+ include: ['posts'],
58
+ limit: 20,
59
+ page: 1,
60
+ name: 'Alice',
61
+ })
62
+
63
+ const users = await bravo.apply()
64
+ const result = await bravo.paginate()
65
+ ```
66
+
67
+ ## Query params
68
+
69
+ Lucid Bravo understands these params out of the box:
70
+
71
+ - `sort.field` and `sort.order`
72
+ - `limit`
73
+ - `page`
74
+ - `include`
75
+ - any custom filter key that matches a camelCase method on your Bravo class
76
+
77
+ For example, `first_name` maps to a `firstName()` method.
78
+
79
+ ## Notes
80
+
81
+ - `LucidBravo` expects to run inside an active HTTP context.
82
+ - Only relations returned by `getAllowedIncludes()` are preloaded.
83
+ - If you want request validation, create a Vine schema in your app that matches the same query shape.
84
+
85
+ ## Authorization
86
+
87
+ If you need authorization inside a Bravo method or a controller that uses the same HTTP context, you can access Bouncer from `this.$http`:
88
+
89
+ ```ts
90
+ const { bouncer } = this.$http
91
+
92
+ await bouncer.authorize(viewPosts)
93
+ await bouncer.with(PostsPolicy).authorize('viewAny')
94
+ ```
95
+
96
+ ## License
97
+
98
+ MIT
@@ -0,0 +1 @@
1
+ {"commands":[],"version":1}
@@ -0,0 +1,4 @@
1
+ import { CommandMetaData, Command } from '@adonisjs/ace/types';
2
+
3
+ export function getMetaData(): Promise<CommandMetaData[]>
4
+ export function getCommand(metaData: CommandMetaData): Promise<Command | null>
@@ -0,0 +1,36 @@
1
+ import { readFile } from 'node:fs/promises'
2
+
3
+ /**
4
+ * In-memory cache of commands after they have been loaded
5
+ */
6
+ let commandsMetaData
7
+
8
+ /**
9
+ * Reads the commands from the "./commands.json" file. Since, the commands.json
10
+ * file is generated automatically, we do not have to validate its contents
11
+ */
12
+ export async function getMetaData() {
13
+ if (commandsMetaData) {
14
+ return commandsMetaData
15
+ }
16
+
17
+ const commandsIndex = await readFile(new URL('./commands.json', import.meta.url), 'utf-8')
18
+ commandsMetaData = JSON.parse(commandsIndex).commands
19
+
20
+ return commandsMetaData
21
+ }
22
+
23
+ /**
24
+ * Imports the command by lookingup its path from the commands
25
+ * metadata
26
+ */
27
+ export async function getCommand(metaData) {
28
+ const commands = await getMetaData()
29
+ const command = commands.find(({ commandName }) => metaData.commandName === commandName)
30
+ if (!command) {
31
+ return null
32
+ }
33
+
34
+ const { default: commandConstructor } = await import(new URL(command.filePath, import.meta.url).href)
35
+ return commandConstructor
36
+ }
@@ -0,0 +1,7 @@
1
+ import { BaseCommand } from '@adonisjs/core/ace';
2
+ export default class MakeBravo extends BaseCommand {
3
+ static commandName: string;
4
+ static description: string;
5
+ name: string;
6
+ run(): Promise<import("@adonisjs/core/types/app").GeneratedStub>;
7
+ }
@@ -0,0 +1,2 @@
1
+ import type Configure from '@adonisjs/core/commands/configure';
2
+ export declare function configure(_command: Configure): Promise<void>;
@@ -0,0 +1,8 @@
1
+ //#region configure.ts
2
+ async function configure(_command) {
3
+ await (await _command.createCodemods()).updateRcFile((rcFile) => {
4
+ rcFile.addCommand("@kadirgun/lucid-bravo/commands");
5
+ });
6
+ }
7
+ //#endregion
8
+ export { configure };
@@ -0,0 +1,2 @@
1
+ export { configure } from './configure.ts';
2
+ export { stubsRoot } from './stubs/main.ts';
package/build/index.js ADDED
@@ -0,0 +1,9 @@
1
+ import { configure } from "./configure.js";
2
+ //#region stubs/main.ts
3
+ /**
4
+ * Path to the root directory where the stubs are stored. We use
5
+ * this path within commands and the configure hook
6
+ */
7
+ const stubsRoot = import.meta.dirname;
8
+ //#endregion
9
+ export { configure, stubsRoot };
@@ -0,0 +1,48 @@
1
+ import type { LucidModel, ModelAttributes, ModelQueryBuilderContract } from '@adonisjs/lucid/types/model';
2
+ import type { BravoParams, BravoSortOption } from './types.ts';
3
+ import { HttpContext } from '@adonisjs/core/http';
4
+ export declare abstract class LucidBravo<T extends LucidModel> {
5
+ protected $query: ModelQueryBuilderContract<T>;
6
+ protected $params: BravoParams;
7
+ protected $http: HttpContext;
8
+ protected $countQuery: ModelQueryBuilderContract<T>;
9
+ protected defaultLimit: number;
10
+ protected defaultSort: BravoSortOption | null;
11
+ constructor(query: ModelQueryBuilderContract<T>, params: BravoParams);
12
+ static build<T extends LucidModel, B extends LucidBravo<T>>(this: {
13
+ new (query: ModelQueryBuilderContract<T>, params: BravoParams): B;
14
+ }, query: ModelQueryBuilderContract<T>, params: BravoParams): B;
15
+ /**
16
+ * Return a whitelist of sortable columns
17
+ */
18
+ getSortable(): (keyof ModelAttributes<InstanceType<LucidModel>> | {})[];
19
+ /**
20
+ * Return a whitelist of allowed relations for preload include
21
+ */
22
+ getAllowedIncludes(): string[];
23
+ /**
24
+ * Main entry point to apply all filters, includes, sorting and pagination
25
+ */
26
+ apply(): Promise<InstanceType<T>[]>;
27
+ count(): Promise<number>;
28
+ paginate(): Promise<{
29
+ items: InstanceType<T>[];
30
+ total: number;
31
+ }>;
32
+ /**
33
+ * Automatically call methods that match camelCase version of snake_case params
34
+ */
35
+ protected applyFilters(): Promise<void>;
36
+ /**
37
+ * Apply preload include relations based on allowlist
38
+ */
39
+ protected applyIncludes(): Promise<void>;
40
+ /**
41
+ * Apply sorting based on sort[field] and sort[order] params
42
+ */
43
+ protected applySorting(): Promise<void>;
44
+ /**
45
+ * Apply simple limit and offset pagination
46
+ */
47
+ protected applyPagination(): Promise<void>;
48
+ }
@@ -0,0 +1,15 @@
1
+ export type SortOrder = 'asc' | 'desc';
2
+ export interface BravoSortOption {
3
+ field: string;
4
+ order: SortOrder;
5
+ }
6
+ export interface BravoParams {
7
+ page?: number;
8
+ limit?: number;
9
+ sort?: {
10
+ field?: string;
11
+ order?: SortOrder;
12
+ };
13
+ include?: string[];
14
+ [key: string]: any;
15
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Path to the root directory where the stubs are stored. We use
3
+ * this path within commands and the configure hook
4
+ */
5
+ export declare const stubsRoot: string;
@@ -0,0 +1,20 @@
1
+ {{#var modelName = generators.modelName(entity.name)}}
2
+ {{#var modelFileName = generators.modelFileName(entity.name)}}
3
+ {{#var bravoFileName = modelFileName.replace(/\.ts$/, '_bravo.ts')}}
4
+ {{#var modelImportPath = generators.importPath('#models', entity.path, modelFileName.replace(/\.ts$/, ''))}}
5
+ {{{
6
+ exports({
7
+ to: app.makePath('app/bravos', entity.path, bravoFileName)
8
+ })
9
+ }}}
10
+ import { LucidBravo } from '@kadirgun/lucid-bravo'
11
+ import type {{ entity.name }} from '{{ modelImportPath }}'
12
+ import type { ModelAttributes } from '@adonisjs/lucid/types/model'
13
+
14
+ export default class {{ modelName }}Bravo extends LucidBravo<typeof {{ entity.name }}> {
15
+ public override getSortable(): string[] {
16
+ return []
17
+ }
18
+
19
+ protected defaultLimit = 20
20
+ }
@@ -0,0 +1,60 @@
1
+ export declare const bravoSchema: {
2
+ sort: import("@vinejs/vine").OptionalModifier<import("@vinejs/vine").VineObject<{
3
+ field: import("@vinejs/vine").VineString;
4
+ order: import("@vinejs/vine").VineEnum<readonly ["asc", "desc"]>;
5
+ }, {
6
+ field: string;
7
+ order: "asc" | "desc";
8
+ }, {
9
+ field: string;
10
+ order: "asc" | "desc";
11
+ }, {
12
+ field: string;
13
+ order: "asc" | "desc";
14
+ }>>;
15
+ limit: import("@vinejs/vine/schema/base/literal").OptionalModifier<import("@vinejs/vine").VineNumber>;
16
+ page: import("@vinejs/vine/schema/base/literal").OptionalModifier<import("@vinejs/vine").VineNumber>;
17
+ include: import("@vinejs/vine").OptionalModifier<import("@vinejs/vine").VineArray<import("@vinejs/vine").VineString>>;
18
+ };
19
+ export declare const bravoValidator: import("@vinejs/vine").VineValidator<import("@vinejs/vine").VineObject<{
20
+ sort: import("@vinejs/vine").OptionalModifier<import("@vinejs/vine").VineObject<{
21
+ field: import("@vinejs/vine").VineString;
22
+ order: import("@vinejs/vine").VineEnum<readonly ["asc", "desc"]>;
23
+ }, {
24
+ field: string;
25
+ order: "asc" | "desc";
26
+ }, {
27
+ field: string;
28
+ order: "asc" | "desc";
29
+ }, {
30
+ field: string;
31
+ order: "asc" | "desc";
32
+ }>>;
33
+ limit: import("@vinejs/vine/schema/base/literal").OptionalModifier<import("@vinejs/vine").VineNumber>;
34
+ page: import("@vinejs/vine/schema/base/literal").OptionalModifier<import("@vinejs/vine").VineNumber>;
35
+ include: import("@vinejs/vine").OptionalModifier<import("@vinejs/vine").VineArray<import("@vinejs/vine").VineString>>;
36
+ }, {
37
+ page?: string | number | null | undefined;
38
+ limit?: string | number | null | undefined;
39
+ sort?: {
40
+ field: string;
41
+ order: "asc" | "desc";
42
+ } | null | undefined;
43
+ include?: string[] | null | undefined;
44
+ }, {
45
+ page?: number | undefined;
46
+ limit?: number | undefined;
47
+ sort?: {
48
+ field: string;
49
+ order: "asc" | "desc";
50
+ } | undefined;
51
+ include?: string[] | undefined;
52
+ }, {
53
+ page?: number | undefined;
54
+ limit?: number | undefined;
55
+ sort?: {
56
+ field: string;
57
+ order: "asc" | "desc";
58
+ } | undefined;
59
+ include?: string[] | undefined;
60
+ }>, Record<string, any> | undefined>;
package/package.json ADDED
@@ -0,0 +1,134 @@
1
+ {
2
+ "name": "@kadirgun/lucid-bravo",
3
+ "description": "A powerful, fluent query builder for AdonisJS Lucid to handle filtering, sorting and pagination in a single flow",
4
+ "version": "0.0.1",
5
+ "engines": {
6
+ "node": ">=24.0.0"
7
+ },
8
+ "type": "module",
9
+ "files": [
10
+ "build",
11
+ "!build/bin",
12
+ "!build/tests"
13
+ ],
14
+ "main": "build/index.js",
15
+ "exports": {
16
+ ".": "./build/index.js",
17
+ "./types": "./build/src/types.js"
18
+ },
19
+ "scripts": {
20
+ "copy:templates": "copyfiles \"stubs/**/*.stub\" build",
21
+ "typecheck": "tsc --noEmit",
22
+ "lint": "eslint .",
23
+ "format": "prettier --write .",
24
+ "quick:test": "node --import=@poppinss/ts-exec --enable-source-maps bin/test.ts",
25
+ "pretest": "pnpm lint",
26
+ "test": "c8 node --import=@poppinss/ts-exec --enable-source-maps bin/test.ts",
27
+ "precompile": "pnpm lint",
28
+ "compile": "tsdown && tsc --emitDeclarationOnly --declaration",
29
+ "postcompile": "pnpm copy:templates && pnpm index:commands",
30
+ "build": "pnpm compile",
31
+ "release": "release-it",
32
+ "version": "pnpm build",
33
+ "prepublishOnly": "pnpm build",
34
+ "index:commands": "adonis-kit index build/commands"
35
+ },
36
+ "keywords": [
37
+ "adonisjs",
38
+ "lucid",
39
+ "query builder",
40
+ "filtering",
41
+ "sorting",
42
+ "pagination"
43
+ ],
44
+ "author": "kadirgun",
45
+ "license": "MIT",
46
+ "devDependencies": {
47
+ "@adonisjs/assembler": "^8.0.0",
48
+ "@adonisjs/auth": "^10.0.0",
49
+ "@adonisjs/core": "^7.0.1",
50
+ "@adonisjs/eslint-config": "^3.0.0",
51
+ "@adonisjs/lucid": "^22.4.1",
52
+ "@adonisjs/prettier-config": "^1.4.5",
53
+ "@adonisjs/tsconfig": "^2.0.0",
54
+ "@japa/assert": "^4.2.0",
55
+ "@japa/file-system": "^3.0.0",
56
+ "@japa/runner": "^5.3.0",
57
+ "@poppinss/ts-exec": "^1.4.4",
58
+ "@release-it/conventional-changelog": "^10.0.5",
59
+ "@types/node": "^25.3.5",
60
+ "@vinejs/vine": "^4.3.0",
61
+ "better-sqlite3": "^12.8.0",
62
+ "c8": "^11.0.0",
63
+ "copyfiles": "^2.4.1",
64
+ "cross-env": "^10.1.0",
65
+ "eslint": "^10.0.3",
66
+ "luxon": "^3.7.2",
67
+ "prettier": "^3.8.1",
68
+ "release-it": "^19.2.4",
69
+ "tsdown": "^0.21.0",
70
+ "typescript": "^5.9.3"
71
+ },
72
+ "peerDependencies": {
73
+ "@adonisjs/assembler": "^8.0.0",
74
+ "@adonisjs/core": "^7.0.0"
75
+ },
76
+ "peerDependenciesMeta": {
77
+ "@adonisjs/assembler": {
78
+ "optional": true
79
+ }
80
+ },
81
+ "publishConfig": {
82
+ "access": "public",
83
+ "provenance": true
84
+ },
85
+ "tsdown": {
86
+ "entry": [
87
+ "./index.ts",
88
+ "./configure.ts"
89
+ ],
90
+ "outDir": "./build",
91
+ "clean": true,
92
+ "format": "esm",
93
+ "minify": "dce-only",
94
+ "fixedExtension": false,
95
+ "dts": false,
96
+ "treeshake": false,
97
+ "sourcemaps": false,
98
+ "target": "esnext"
99
+ },
100
+ "release-it": {
101
+ "git": {
102
+ "requireCleanWorkingDir": true,
103
+ "requireUpstream": true,
104
+ "commitMessage": "chore(release): ${version}",
105
+ "tagAnnotation": "v${version}",
106
+ "push": true,
107
+ "tagName": "v${version}"
108
+ },
109
+ "github": {
110
+ "release": true
111
+ },
112
+ "npm": {
113
+ "publish": true,
114
+ "skipChecks": true
115
+ },
116
+ "plugins": {
117
+ "@release-it/conventional-changelog": {
118
+ "preset": {
119
+ "name": "angular"
120
+ }
121
+ }
122
+ }
123
+ },
124
+ "c8": {
125
+ "reporter": [
126
+ "text",
127
+ "html"
128
+ ],
129
+ "exclude": [
130
+ "tests/**"
131
+ ]
132
+ },
133
+ "prettier": "@adonisjs/prettier-config"
134
+ }