@nano-app/plugins 0.7.1 → 0.9.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/README.md CHANGED
@@ -20,19 +20,44 @@ createNanoApp({ plugins: [health()] });
20
20
  | Plugin | Import | Endpoints | Options |
21
21
  | -------- | ----------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------- |
22
22
  | `health` | `import health from '@nano-app/plugins/health'` | `GET /health` → `{ success: true, result: { status: "ok" } }` | `basePath` (default `"/health"`) |
23
- | `crud` | `import crud from '@nano-app/plugins/crud'` | On the models listed in `models` (any other answers 404): `GET` and `QUERY` on `/api/<model>{/<id>}` → a list `{ result, count }` or one record, with `QueryParams` as the body of `QUERY`; `POST /api/<model>`, `PUT` and `DELETE` on `/api/<model>/<id>` → the record created, updated or deleted. `<id>` takes the type of the model's id (`Int`, `BigInt` or `String`). With Better Auth, each method asks for a permission on the model: `read` (`GET`, `QUERY`), `create`, `update`, `delete` | `models` (the published ones), `basePath` (default `"/api"`) |
24
- | `rate-limit` | `import rateLimit from '@nano-app/plugins/rate-limit'` | None: limits every request of the routes and plugins mounted after it, per client IP (see [Client IP](../backend/README.md#client-ip)). Each request spends a token of the client's bucket, which holds `capacity` and refills `refillPerSecond` tokens per second; without one it answers `429` with `message` and `Retry-After` (seconds until the next token). List it first in `plugins`. The buckets live in the memory of each process | `capacity` (default `100`), `refillPerSecond` (default `1`), `message` |
23
+ | `crud` | `import crud from '@nano-app/plugins/crud'` | On the tables listed in `models`, by their name in the app's schema (any other answers 404): `GET` and `QUERY` on `/api/<model>{/<id>}` → a list `{ result }` or one record, with `QueryParams` as the body of `QUERY`: Drizzle's relational query (`where`, `columns`, `orderBy`, `limit`, `offset`, `with`); `POST /api/<model>`, `PUT` and `DELETE` on `/api/<model>/<id>` → the record created, updated or deleted. Postgres casts `<id>` to the type of the `id` column. With Better Auth, each method asks for a permission on the table: `read` (`GET`, `QUERY`), `create`, `update`, `delete`, see [crud and related tables](#crud-and-related-tables) | `models` (the published ones), `dbSchema` (the app's Drizzle schema, as in `mainPlugin.database`), `validations` (zod schemas of the bodies, see [crud and the bodies](#crud-and-the-bodies)), `basePath` (default `"/api"`) |
24
+ | `rate-limit` | `import rateLimit from '@nano-app/plugins/rate-limit'` | None: limits every request of the routes and plugins mounted after it, per client IP (see [Client IP](../backend/README.md#client-ip)); the addresses of an IPv6 `/56` network are one client. Each request spends a token of the client's bucket, which holds `capacity` and refills `refillPerSecond` tokens per second; without one it answers `429` with `message` and `Retry-After` (seconds until the next token). List it first in `plugins`. The buckets live in the memory of each process | `capacity` (default `100`), `refillPerSecond` (default `1`), `message` |
25
25
 
26
26
  What is not CRUD, such as creating a record with business logic, goes in a route of your own with its own URL: a route of yours on a `crud` URL takes every method of it.
27
27
 
28
+ ### crud and the bodies
29
+
30
+ `crud` sends each body to Drizzle as it came: any column of the table can be written, and a `QUERY` can ask for any `limit` (100 without one). What a body may bring is up to the app: `validations` takes, per model, a [zod](https://zod.dev) schema by action, the same names as the permissions: `read` (the body of `QUERY`, and `{}` for `GET`), `create` (`POST`) and `update` (`PUT`). A body that breaks its validation answers 400 with the field and the message of zod; one that passes goes on as zod gives it, so a validation also drops the keys it does not name and sets its defaults. [`drizzle-orm/zod`](https://orm.drizzle.team/docs/zod) builds them from the table:
31
+
32
+ ```ts
33
+ import { createInsertSchema, createUpdateSchema } from 'drizzle-orm/zod';
34
+ import { z } from 'zod';
35
+ import * as schema from './db/schema';
36
+
37
+ crud({
38
+ models: ['note'],
39
+ dbSchema: schema,
40
+ validations: {
41
+ note: {
42
+ create: createInsertSchema(schema.note).omit({ id: true }),
43
+ update: createUpdateSchema(schema.note).omit({ id: true }),
44
+ read: z.looseObject({ limit: z.number().max(50).default(20) }),
45
+ },
46
+ },
47
+ });
48
+ ```
49
+
50
+ ### crud and related tables
51
+
52
+ A `crud` query runs on the app's client, so it reaches the related tables Drizzle's relations give: `with` loads them and `where` filters by them, also the ones that are not in `models`. With Better Auth, the permission asked is only the one of the URL's table. What a query may load is up to the app: the `read` validation of the model decides it (a `z.strictObject` without `with` keeps a query in its table). Better Auth's tables (`user`, `account` with its password hashes, `session` with its tokens) hold secrets: never publish `account`, `session` or `verification`, and do not relate them to a published table without a `read` validation that leaves them out.
53
+
28
54
  ### Layout
29
55
 
30
56
  ```
31
57
  plugins/
32
58
  └── <name>/
33
59
  ├── index.ts default-exports the plugin factory: the import path
34
- ├── schema.prisma its tables, when it has any
35
- ├── migrations/ their migrations, applied at startup
60
+ ├── schema.ts its tables, when it has any, in the Postgres schema nano_<name>
36
61
  └── routes/ *.route.ts, mounted under the plugin's basePath
37
62
  ```
38
63
 
@@ -110,20 +135,9 @@ Use MIT or Apache-2.0 if you want the plugin listed from this repo later. Open a
110
135
 
111
136
  ### Database
112
137
 
113
- Optional. Set `database: { enabled: true, schemaPath }` on the plugin config. The schema must be PostgreSQL. Schemas starting with `nano_` are reserved for the official plugins: a schema inside the `@nano-app/plugins` package declares only `nano_*` schemas, and every other schema declares none.
114
-
115
- At startup nano-app generates the plugin's client in `.nano-app/prisma-clients/<name>` (again only when the schema changed) and checks that every model can be read.
116
-
117
- - **A plugin of yours, or from another package:** its tables are applied with Prisma by whoever installs it, like the app's schema.
118
- - **An official plugin:** nano-app also migrates it, so the consumer runs nothing. Its schema ships in `build/<name>/schema.prisma` with a `migrations/` folder next to it. At startup `prisma migrate deploy` applies the pending ones to the plugin's first `nano_*` schema, where its history (`_prisma_migrations`) lives apart from the app's. Each migration runs once, in a transaction, one instance at a time.
119
-
120
- #### Migrations of an official plugin
121
-
122
- - Every schema change ships its own `migrations/<timestamp>_<name>/migration.sql`, reviewed like code. A published migration is never edited.
123
- - Migrations only add: tables, nullable columns or columns with a default, indexes. Dropping or renaming takes two releases: stop using it first, remove it later.
124
- - The database user of the consumer needs to create tables in the plugin's `nano_*` schema.
138
+ Optional. Pass `database: { schema }` on the plugin config: the module of its Drizzle tables, with its `relations` when it has them. Its tables live in the Postgres schema `nano_<plugin name>`, which drizzle-kit creates when the module exports its `pgSchema`; a table elsewhere fails the startup.
125
139
 
126
- Handlers and callbacks receive that client as `params.db`. Type it with `createRoute<{ db: PrismaClient }>`, passing your generated `PrismaClient`.
140
+ Its tables are applied with drizzle-kit by whoever installs it, like the app's schema. Handlers and callbacks receive its client as `params.db`.
127
141
 
128
142
  ### What belongs in this repository
129
143
 
@@ -1,9 +1,15 @@
1
- /** Automatic CRUD: the listed models of the app's database on `/api/<model>{/<id>}` */
1
+ import { CrudValidations } from "../types/crud.js";
2
+ import { NanoObject } from "@nano-app/backend";
3
+ /** Automatic CRUD: the listed tables of the app's database on `/api/<model>{/<id>}` */
2
4
  declare const _default: (options?: {
3
5
  basePath?: string;
4
6
  models: string[];
7
+ dbSchema: NanoObject;
8
+ validations?: NanoObject<CrudValidations>;
5
9
  } | undefined) => import("@nano-app/backend").PluginConfig<{
6
10
  basePath?: string;
7
11
  models: string[];
12
+ dbSchema: NanoObject;
13
+ validations?: NanoObject<CrudValidations>;
8
14
  }>;
9
15
  export { _default as default };
@@ -1,13 +1,12 @@
1
1
  import { createPlugin } from "@nano-app/backend";
2
- import { dirname, resolve } from "node:path";
3
- import { fileURLToPath } from "node:url";
2
+ import { join } from "node:path";
4
3
  // crud/index.ts
5
- /** Automatic CRUD: the listed models of the app's database on `/api/<model>{/<id>}` */
4
+ /** Automatic CRUD: the listed tables of the app's database on `/api/<model>{/<id>}` */
6
5
  var crud_default = createPlugin((options) => ({
7
6
  name: "crud",
8
7
  basePath: options?.basePath ?? "/api",
9
8
  stage: "after",
10
- routesDir: resolve(dirname(fileURLToPath(import.meta.url)), "routes"),
9
+ routesDir: join(import.meta.dirname, "routes"),
11
10
  options
12
11
  }));
13
12
  export { crud_default as default };
@@ -1,7 +1,7 @@
1
- import Query from "../Query.js";
2
1
  import { NanoError, createRoute, isGranted } from "@nano-app/backend";
2
+ import { eq } from "drizzle-orm";
3
3
  // crud/routes/index.route.ts
4
- /** Permission of Better Auth that each method needs on the URL's model */
4
+ /** Action of each method: its permission of Better Auth and the validation of its body */
5
5
  const ACTIONS = {
6
6
  GET: "read",
7
7
  QUERY: "read",
@@ -9,38 +9,70 @@ const ACTIONS = {
9
9
  PUT: "update",
10
10
  DELETE: "delete"
11
11
  };
12
- /** Conversion of the URL's id to the type of the model's id, when it is not a string */
13
- const ID_TYPES = {
14
- Int: Number,
15
- BigInt
16
- };
17
- /** Reads a list, or one record, with the `QueryParams` of the body */
18
- async function read(oReq, { onBeforeResult }) {
19
- return Query.read(onBeforeResult?.model, oReq.body ?? {}, onBeforeResult?.where);
12
+ /** Records a list answers when the request sends no `limit` */
13
+ const DEFAULT_LIMIT = 100;
14
+ /** The first record of a query or a write: 404 without it */
15
+ function first(aRecords) {
16
+ if (!aRecords[0]) throw new NanoError("Not found", 404);
17
+ return { result: aRecords[0] };
18
+ }
19
+ /** Every record of a query */
20
+ function list(aRecords) {
21
+ return { result: aRecords };
22
+ }
23
+ /** A list of the table, or one record by its id, with Drizzle's relational query of the body */
24
+ async function read(_oReq, { db, onBeforeResult }) {
25
+ const { model, page, answer, body } = onBeforeResult ?? {};
26
+ return answer(await db.query[model].findMany({
27
+ limit: DEFAULT_LIMIT,
28
+ ...body,
29
+ ...page
30
+ }));
20
31
  }
21
32
  /** `GET` reads without parameters, `QUERY` with `QueryParams` as its body */
22
33
  var index_route_default = createRoute({
23
34
  expression: "/:model{/:id}",
24
35
  callbacks: { onBefore: async (oReq, sMethod, oParams) => {
25
36
  const sModel = String(oReq.params.model);
37
+ const sAction = ACTIONS[sMethod];
26
38
  const { id } = oReq.params;
27
- if (!oParams.models.includes(sModel)) throw new NanoError("Not found", 404);
28
- if (!await isGranted(oParams, { [sModel]: [ACTIONS[sMethod]] })) throw new NanoError("Forbidden", 403);
29
- const oModel = oParams.db[sModel];
30
- if (!id) return { model: oModel };
31
- const sId = String(id);
39
+ const oTable = oParams.dbSchema[sModel];
40
+ if (!oParams.models.includes(sModel) || !oTable) throw new NanoError("Not found", 404);
41
+ if (!await isGranted(oParams, { [sModel]: [sAction] })) throw new NanoError("Forbidden", 403);
42
+ const oBody = oReq.body ?? {};
43
+ const oResult = (oParams.validations?.[sModel]?.[sAction])?.safeParse(oBody) ?? { data: oBody };
44
+ if (oResult.error) {
45
+ const { path, message } = oResult.error.issues[0];
46
+ throw new NanoError([...path, message].join(": "), 400);
47
+ }
48
+ const oRead = id ? {
49
+ page: {
50
+ where: { id },
51
+ limit: 1
52
+ },
53
+ answer: first
54
+ } : { answer: list };
32
55
  return {
33
- model: oModel,
34
- where: { id: ID_TYPES[oModel.fields.id.typeName]?.(sId) ?? sId }
56
+ model: sModel,
57
+ table: oTable,
58
+ id,
59
+ body: oResult.data,
60
+ ...oRead
35
61
  };
36
62
  } },
37
63
  GET: read,
38
64
  QUERY: read,
39
- POST: async (oReq, { onBeforeResult }) => ({ result: await onBeforeResult?.model.create({ data: oReq.body }) }),
40
- PUT: async (oReq, { onBeforeResult }) => ({ result: await onBeforeResult?.model.update({
41
- where: onBeforeResult.where,
42
- data: oReq.body
43
- }) }),
44
- DELETE: async (_oReq, { onBeforeResult }) => ({ result: await onBeforeResult?.model.delete({ where: onBeforeResult.where }) })
65
+ POST: async (_oReq, { db, onBeforeResult }) => {
66
+ const { table, body } = onBeforeResult ?? {};
67
+ return first(await db.insert(table).values(body).returning());
68
+ },
69
+ PUT: async (_oReq, { db, onBeforeResult }) => {
70
+ const { table, id, body } = onBeforeResult ?? {};
71
+ return first(await db.update(table).set(body).where(eq(table.id, id)).returning());
72
+ },
73
+ DELETE: async (_oReq, { db, onBeforeResult }) => {
74
+ const { table, id } = onBeforeResult ?? {};
75
+ return first(await db.delete(table).where(eq(table.id, id)).returning());
76
+ }
45
77
  });
46
78
  export { index_route_default as default };
@@ -1,12 +1,11 @@
1
1
  import { createPlugin } from "@nano-app/backend";
2
- import { dirname, resolve } from "node:path";
3
- import { fileURLToPath } from "node:url";
2
+ import { join } from "node:path";
4
3
  // health/index.ts
5
4
  /** Health check: `GET /health` answers `{ status: "ok" }` while the server is up. */
6
5
  var health_default = createPlugin((options) => ({
7
6
  name: "health",
8
7
  basePath: options?.basePath ?? "/health",
9
8
  stage: "before",
10
- routesDir: resolve(dirname(fileURLToPath(import.meta.url)), "routes")
9
+ routesDir: join(import.meta.dirname, "routes")
11
10
  }));
12
11
  export { health_default as default };
@@ -1,3 +1,4 @@
1
+ import { ipKeyGenerator } from "express-rate-limit";
1
2
  import { createPlugin } from "@nano-app/backend";
2
3
  // rate-limit/index.ts
3
4
  /**
@@ -18,7 +19,7 @@ var rate_limit_default = createPlugin((options) => {
18
19
  for (const [sIp, oBucket] of oBuckets) if (fnRefill(oBucket, iNow) >= capacity) oBuckets.delete(sIp);
19
20
  }, 6e4).unref();
20
21
  oApp.use((oReq, oRes, fnNext) => {
21
- const sIp = oReq.ip ?? "";
22
+ const sIp = ipKeyGenerator(oReq.ip ?? "");
22
23
  const iNow = Date.now();
23
24
  const iTokens = fnRefill(oBuckets.get(sIp) ?? {
24
25
  iTokens: capacity,
@@ -0,0 +1,10 @@
1
+ import { ZodType } from "zod";
2
+ /** Validations of a model: a zod schema by action, each one optional */
3
+ export type CrudValidations = {
4
+ /** Body of a `QUERY`, and `{}` for a `GET` */
5
+ read?: ZodType;
6
+ /** Body of a `POST` */
7
+ create?: ZodType;
8
+ /** Body of a `PUT` */
9
+ update?: ZodType;
10
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nano-app/plugins",
3
- "version": "0.7.1",
3
+ "version": "0.9.0",
4
4
  "description": "Official plugins for @nano-app/backend",
5
5
  "type": "module",
6
6
  "exports": {
@@ -15,7 +15,7 @@
15
15
  ],
16
16
  "scripts": {
17
17
  "build": "tsdown",
18
- "test": "tsx --env-file-if-exists=../.env --test tests/*.test.ts",
18
+ "test": "tsx --env-file-if-exists=../.env --test --test-concurrency=1 tests/*.test.ts",
19
19
  "prepublishOnly": "pnpm run build"
20
20
  },
21
21
  "keywords": [
@@ -37,21 +37,34 @@
37
37
  "node": "^22.23.4 || ^24.22.1 || >=26.12.1"
38
38
  },
39
39
  "peerDependencies": {
40
- "@nano-app/backend": ">=0.15.0"
40
+ "@nano-app/backend": ">=0.15.0",
41
+ "drizzle-orm": "^1.0.0-rc.5",
42
+ "zod": "^4.6.7"
41
43
  },
42
44
  "devDependencies": {
43
45
  "@happy-dom/global-registrator": "^21.0.4",
44
46
  "@nano-app/backend": "workspace:*",
45
- "@prisma/adapter-pg": "^7.10.1",
46
- "@prisma/client": "^7.10.1",
47
47
  "@types/node": "^26.6.6",
48
48
  "@types/pg": "^8.23.1",
49
+ "drizzle-kit": "^1.0.0-rc.5",
50
+ "drizzle-orm": "^1.0.0-rc.5",
49
51
  "glob": "^14.0.4",
50
52
  "next": "^16.4.5",
51
53
  "pg": "^8.23.1",
52
- "prisma": "^7.10.1",
53
54
  "tsdown": "^0.23.5",
54
55
  "tsx": "^4.23.15",
55
- "typescript": "^7.0.2"
56
+ "typescript": "^7.0.2",
57
+ "zod": "^4.6.7"
58
+ },
59
+ "peerDependenciesMeta": {
60
+ "drizzle-orm": {
61
+ "optional": true
62
+ },
63
+ "zod": {
64
+ "optional": true
65
+ }
66
+ },
67
+ "dependencies": {
68
+ "express-rate-limit": "^8.7.3"
56
69
  }
57
70
  }
@@ -1,62 +0,0 @@
1
- // crud/Query.ts
2
- /** Records a list answers when the request sends no `top` */
3
- const DEFAULT_TOP = 100;
4
- /** Reads a model of the app's Prisma client with core's `QueryParams` */
5
- var Query = class Query {
6
- /** A list of the model with its total, or one record by its `where` */
7
- static async read(oModel, oQuery, oWhere) {
8
- const oArgs = Query.toPrisma(oQuery);
9
- if (oWhere) {
10
- const { select, include } = oArgs;
11
- return { result: await oModel.findUniqueOrThrow({
12
- where: oWhere,
13
- select,
14
- include
15
- }) };
16
- }
17
- const [aRecords, iCount] = await Promise.all([oModel.findMany(oArgs), oModel.count({ where: oArgs.where })]);
18
- return {
19
- result: aRecords,
20
- count: iCount
21
- };
22
- }
23
- /** `filter` → `where`, `orderby` → `orderBy`, `top`/`skip` → `take`/`skip`, `select` and `expand` → `select` or `include` */
24
- static toPrisma(oQuery) {
25
- const { filter, orderby, top, skip, select, expand } = oQuery;
26
- const oInclude = expand ? Query.include(Query.list(expand)) : void 0;
27
- const oSelect = select ? Query.fields(Query.list(select), oInclude) : void 0;
28
- return {
29
- where: filter,
30
- orderBy: orderby && Object.entries(orderby).map(([sPath, sDirection]) => Query.nest(sPath.split("."), sDirection)),
31
- take: top ?? DEFAULT_TOP,
32
- skip,
33
- select: oSelect,
34
- include: oSelect ? void 0 : oInclude
35
- };
36
- }
37
- /** `['user', 'name']`, `'asc'` → `{ user: { name: 'asc' } }` */
38
- static nest(aPath, sValue) {
39
- const [sField, ...aRest] = aPath;
40
- return { [sField]: aRest.length ? Query.nest(aRest, sValue) : sValue };
41
- }
42
- /** `['user', 'posts.comments']` → `{ user: true, posts: { include: { comments: true } } }` */
43
- static include(aPaths) {
44
- const aRelations = [...new Set(aPaths.map((sPath) => sPath.split(".")[0]))];
45
- return Object.fromEntries(aRelations.map((sRelation) => {
46
- const aNested = aPaths.filter((sPath) => sPath.startsWith(`${sRelation}.`)).map((sPath) => sPath.slice(sRelation.length + 1));
47
- return [sRelation, aNested.length ? { include: Query.include(aNested) } : true];
48
- }));
49
- }
50
- /** `['id', 'name']` → `{ id: true, name: true }`, plus the relations to load */
51
- static fields(aFields, oInclude) {
52
- return {
53
- ...Object.fromEntries(aFields.map((sField) => [sField, true])),
54
- ...oInclude
55
- };
56
- }
57
- /** `"a, b"` → `['a', 'b']` */
58
- static list(sList) {
59
- return sList.split(",").map((sItem) => sItem.trim());
60
- }
61
- };
62
- export { Query as default };