@smounters/data 2.3.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/CHANGELOG.md +15 -0
- package/LICENSE +21 -0
- package/README.md +62 -0
- package/dist/base.d.ts +26 -0
- package/dist/base.js +64 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +7 -0
- package/dist/user-setting.d.ts +28 -0
- package/dist/user-setting.js +50 -0
- package/package.json +54 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 2.3.0 - 2026-07-30
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
- Первые фрагменты: `BaseEntity` (первичный ключ UUIDv7), `AuditableEntity` (+ колонки аудита),
|
|
7
|
+
`UserSettingBase` (мешок настроек пользователя: секция/ключ/JSON-значение).
|
|
8
|
+
|
|
9
|
+
Публикуется потому, что появился реальный потребитель: `smounters-apps` наследует базу во всех 111
|
|
10
|
+
сущностях, а `UserSetting` объявляет только таблицу, связь с юзером и уникальность. Схема при переходе
|
|
11
|
+
не изменилась — проверено дампом из метаданных и сравнением расхождения с живой базой до/после.
|
|
12
|
+
|
|
13
|
+
Фрагмент — абстрактный класс БЕЗ `@Entity`: колонки в пакете, таблица и связи в проекте. Требует
|
|
14
|
+
PostgreSQL 18+ (нативная `uuidv7()`). Проекту с ЧИСЛОВЫМ первичным ключом фрагменты не подходят —
|
|
15
|
+
это осознанная граница, а не недоработка.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Sergio (@smounters)
|
|
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,62 @@
|
|
|
1
|
+
# @smounters/data
|
|
2
|
+
|
|
3
|
+
Готовые куски модели данных для MikroORM: первичный ключ UUIDv7, колонки аудита, мешок настроек
|
|
4
|
+
пользователя.
|
|
5
|
+
|
|
6
|
+
```bash
|
|
7
|
+
npm i @smounters/data @mikro-orm/core @mikro-orm/decorators
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
## Что такое фрагмент
|
|
11
|
+
|
|
12
|
+
Фрагмент — это **абстрактный класс без `@Entity()`**. Колонки принадлежат пакету, а таблица, индексы
|
|
13
|
+
и связи — проекту. Разделение не случайное: колонки у всех проектов одинаковые, внешние ключи —
|
|
14
|
+
никогда. Поэтому пакет не может объявить связь с вашим пользователем, а вы не обязаны переписывать
|
|
15
|
+
одни и те же четыре колонки аудита в каждом новом сервисе.
|
|
16
|
+
|
|
17
|
+
| фрагмент | колонки |
|
|
18
|
+
|---|---|
|
|
19
|
+
| `BaseEntity` | `id` — `uuid`, `default uuidv7()` |
|
|
20
|
+
| `AuditableEntity` | то же + `created_at`, `updated_at` (`timestamptz`, серверные значения по умолчанию, `updated_at` обновляется на записи), `created_by`, `updated_by` (`uuid`, допускают NULL) |
|
|
21
|
+
| `UserSettingBase` | то же + `section` (`varchar(50)`, по умолчанию `default`), `key` (`varchar(100)`), `value` (`jsonb`, допускает NULL) |
|
|
22
|
+
|
|
23
|
+
## Как подключить
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { AuditableEntity, UserSettingBase } from "@smounters/data";
|
|
27
|
+
|
|
28
|
+
@Entity({ tableName: "orders" })
|
|
29
|
+
export class Order extends AuditableEntity {
|
|
30
|
+
/* свои колонки */
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// Связь и уникальность объявляет проект — только он знает, где живут его пользователи.
|
|
34
|
+
@Entity({ tableName: "user_settings" })
|
|
35
|
+
@Unique({ properties: ["user", "section", "key"] })
|
|
36
|
+
export class UserSetting extends UserSettingBase {
|
|
37
|
+
@ManyToOne(() => User, { deleteRule: "cascade" })
|
|
38
|
+
@Index()
|
|
39
|
+
user!: Rel<User>;
|
|
40
|
+
}
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`UserSettingBase` — это хранилище, в которое пишет `@smounters/ui` через `UiProvider.useSetting`
|
|
44
|
+
(видимость и порядок колонок таблицы, ширина сайдбара). Значение бэкенд не разбирает: его схему знает
|
|
45
|
+
фронт.
|
|
46
|
+
|
|
47
|
+
## Требования
|
|
48
|
+
|
|
49
|
+
- **PostgreSQL 18+**: `id` берёт значение из `uuidv7()`, а эта функция появилась в 18-й версии. На
|
|
50
|
+
более старом сервере либо завести функцию с таким именем, либо переопределить свойство у себя.
|
|
51
|
+
- `@mikro-orm/core` и `@mikro-orm/decorators` — **peer-зависимости**: ядро ORM в приложении должно
|
|
52
|
+
быть ровно одно, иначе метаданные окажутся в разных реестрах и сущности «не найдутся».
|
|
53
|
+
- Колонки объявлены с ЯВНЫМ типом у каждого декоратора. Ничего не выводится из
|
|
54
|
+
`emitDecoratorMetadata`, поэтому собранный пакет ведёт себя так же, как тот же код внутри
|
|
55
|
+
приложения: отражённые типы через границу пакета не переживают сборку надёжно.
|
|
56
|
+
|
|
57
|
+
## Порядок колонок
|
|
58
|
+
|
|
59
|
+
Унаследованные колонки идут в `CREATE TABLE` перед объявленными в проекте, поэтому у уже
|
|
60
|
+
существующей таблицы порядок в свежем дампе будет другим. На сравнение схемы это не влияет: MikroORM
|
|
61
|
+
сверяет набор колонок, а не их порядок, — проверено на 111 сущностях (расхождение с живой базой до и
|
|
62
|
+
после перехода на фрагменты совпало полностью). Переупорядочить колонки в PostgreSQL всё равно нельзя.
|
package/dist/base.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Primary key only. Use when a table needs no audit columns (a join table, an append-only log with
|
|
3
|
+
* its own timestamp semantics).
|
|
4
|
+
*
|
|
5
|
+
* UUIDv7 (time-ordered, RFC 9562): k-sortable, so B-tree inserts keep the locality of a serial key
|
|
6
|
+
* while the id stays non-enumerable. Generated DB-side into a native `uuid` column — this requires
|
|
7
|
+
* **PostgreSQL 18+**, which ships `uuidv7()`. On older servers install a shim function of that name
|
|
8
|
+
* or override the property in the project.
|
|
9
|
+
*/
|
|
10
|
+
export declare abstract class BaseEntity {
|
|
11
|
+
id: string;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Primary key + audit columns. The default base for aggregates.
|
|
15
|
+
*
|
|
16
|
+
* `createdBy`/`updatedBy` hold the acting user id; null means the system (a worker, a migration, a
|
|
17
|
+
* seed). They are plain uuid columns rather than relations on purpose: a fragment cannot know which
|
|
18
|
+
* table your users live in, and an audit column should not create a foreign key that blocks
|
|
19
|
+
* deleting a user.
|
|
20
|
+
*/
|
|
21
|
+
export declare abstract class AuditableEntity extends BaseEntity {
|
|
22
|
+
createdAt: Date;
|
|
23
|
+
updatedAt: Date;
|
|
24
|
+
createdBy?: string;
|
|
25
|
+
updatedBy?: string;
|
|
26
|
+
}
|
package/dist/base.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
import { PrimaryKey, Property } from "@mikro-orm/decorators/legacy";
|
|
11
|
+
// Entity fragments, not entities: these classes carry NO `@Entity()`. MikroORM inherits decorated
|
|
12
|
+
// properties from an abstract base, so a project extends them and declares its own table name,
|
|
13
|
+
// indexes and relations. That is what makes a fragment reusable across projects whose foreign keys
|
|
14
|
+
// point at different tables.
|
|
15
|
+
//
|
|
16
|
+
// Every decorator here states its column type EXPLICITLY. Nothing is inferred from
|
|
17
|
+
// `emitDecoratorMetadata`, so the built package behaves exactly like the same code compiled inside
|
|
18
|
+
// the consuming project — reflected type metadata does not survive a package boundary reliably.
|
|
19
|
+
/**
|
|
20
|
+
* Primary key only. Use when a table needs no audit columns (a join table, an append-only log with
|
|
21
|
+
* its own timestamp semantics).
|
|
22
|
+
*
|
|
23
|
+
* UUIDv7 (time-ordered, RFC 9562): k-sortable, so B-tree inserts keep the locality of a serial key
|
|
24
|
+
* while the id stays non-enumerable. Generated DB-side into a native `uuid` column — this requires
|
|
25
|
+
* **PostgreSQL 18+**, which ships `uuidv7()`. On older servers install a shim function of that name
|
|
26
|
+
* or override the property in the project.
|
|
27
|
+
*/
|
|
28
|
+
export class BaseEntity {
|
|
29
|
+
}
|
|
30
|
+
__decorate([
|
|
31
|
+
PrimaryKey({ type: "uuid", defaultRaw: "uuidv7()" }),
|
|
32
|
+
__metadata("design:type", String)
|
|
33
|
+
], BaseEntity.prototype, "id", void 0);
|
|
34
|
+
/**
|
|
35
|
+
* Primary key + audit columns. The default base for aggregates.
|
|
36
|
+
*
|
|
37
|
+
* `createdBy`/`updatedBy` hold the acting user id; null means the system (a worker, a migration, a
|
|
38
|
+
* seed). They are plain uuid columns rather than relations on purpose: a fragment cannot know which
|
|
39
|
+
* table your users live in, and an audit column should not create a foreign key that blocks
|
|
40
|
+
* deleting a user.
|
|
41
|
+
*/
|
|
42
|
+
export class AuditableEntity extends BaseEntity {
|
|
43
|
+
constructor() {
|
|
44
|
+
super(...arguments);
|
|
45
|
+
this.createdAt = new Date();
|
|
46
|
+
this.updatedAt = new Date();
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
__decorate([
|
|
50
|
+
Property({ type: "timestamptz", length: 0, defaultRaw: "CURRENT_TIMESTAMP" }),
|
|
51
|
+
__metadata("design:type", Object)
|
|
52
|
+
], AuditableEntity.prototype, "createdAt", void 0);
|
|
53
|
+
__decorate([
|
|
54
|
+
Property({ type: "timestamptz", length: 0, defaultRaw: "CURRENT_TIMESTAMP", onUpdate: () => new Date() }),
|
|
55
|
+
__metadata("design:type", Object)
|
|
56
|
+
], AuditableEntity.prototype, "updatedAt", void 0);
|
|
57
|
+
__decorate([
|
|
58
|
+
Property({ type: "uuid", nullable: true }),
|
|
59
|
+
__metadata("design:type", String)
|
|
60
|
+
], AuditableEntity.prototype, "createdBy", void 0);
|
|
61
|
+
__decorate([
|
|
62
|
+
Property({ type: "uuid", nullable: true }),
|
|
63
|
+
__metadata("design:type", String)
|
|
64
|
+
], AuditableEntity.prototype, "updatedBy", void 0);
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// @smounters/data — MikroORM entity fragments shared by our projects.
|
|
2
|
+
//
|
|
3
|
+
// A fragment is an abstract class WITHOUT `@Entity()`: it owns columns, the project owns the table,
|
|
4
|
+
// the indexes and the relations. That split is deliberate — the columns are the same everywhere, the
|
|
5
|
+
// foreign keys never are.
|
|
6
|
+
export { AuditableEntity, BaseEntity } from "./base.js";
|
|
7
|
+
export { UserSettingBase } from "./user-setting.js";
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Opt } from "@mikro-orm/core";
|
|
2
|
+
import { AuditableEntity } from "./base.js";
|
|
3
|
+
/**
|
|
4
|
+
* Per-user preference bag: one row per (user, section, key), the value is arbitrary JSON. The backend
|
|
5
|
+
* never interprets the value — its shape belongs to the front end (column order and visibility,
|
|
6
|
+
* sidebar width, filters). This is the store `@smounters/ui` writes through `UiProvider.useSetting`.
|
|
7
|
+
*
|
|
8
|
+
* The relation to the user and the unique constraint are declared by the project, because only the
|
|
9
|
+
* project knows which table its users live in:
|
|
10
|
+
*
|
|
11
|
+
* ```ts
|
|
12
|
+
* @Entity({ tableName: "user_settings" })
|
|
13
|
+
* @Unique({ properties: ["user", "section", "key"] })
|
|
14
|
+
* export class UserSetting extends UserSettingBase {
|
|
15
|
+
* @ManyToOne(() => User, { deleteRule: "cascade" })
|
|
16
|
+
* @Index()
|
|
17
|
+
* user!: Rel<User>;
|
|
18
|
+
* }
|
|
19
|
+
* ```
|
|
20
|
+
*
|
|
21
|
+
* `section` carries a default rather than being nullable so that the unique triple always holds — a
|
|
22
|
+
* NULL section would let the same key be inserted twice.
|
|
23
|
+
*/
|
|
24
|
+
export declare abstract class UserSettingBase extends AuditableEntity {
|
|
25
|
+
section: string & Opt;
|
|
26
|
+
key: string;
|
|
27
|
+
value?: unknown;
|
|
28
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
|
|
2
|
+
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
|
|
3
|
+
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
|
|
4
|
+
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
|
|
5
|
+
return c > 3 && r && Object.defineProperty(target, key, r), r;
|
|
6
|
+
};
|
|
7
|
+
var __metadata = (this && this.__metadata) || function (k, v) {
|
|
8
|
+
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
|
|
9
|
+
};
|
|
10
|
+
import { Property } from "@mikro-orm/decorators/legacy";
|
|
11
|
+
import { AuditableEntity } from "./base.js";
|
|
12
|
+
/**
|
|
13
|
+
* Per-user preference bag: one row per (user, section, key), the value is arbitrary JSON. The backend
|
|
14
|
+
* never interprets the value — its shape belongs to the front end (column order and visibility,
|
|
15
|
+
* sidebar width, filters). This is the store `@smounters/ui` writes through `UiProvider.useSetting`.
|
|
16
|
+
*
|
|
17
|
+
* The relation to the user and the unique constraint are declared by the project, because only the
|
|
18
|
+
* project knows which table its users live in:
|
|
19
|
+
*
|
|
20
|
+
* ```ts
|
|
21
|
+
* @Entity({ tableName: "user_settings" })
|
|
22
|
+
* @Unique({ properties: ["user", "section", "key"] })
|
|
23
|
+
* export class UserSetting extends UserSettingBase {
|
|
24
|
+
* @ManyToOne(() => User, { deleteRule: "cascade" })
|
|
25
|
+
* @Index()
|
|
26
|
+
* user!: Rel<User>;
|
|
27
|
+
* }
|
|
28
|
+
* ```
|
|
29
|
+
*
|
|
30
|
+
* `section` carries a default rather than being nullable so that the unique triple always holds — a
|
|
31
|
+
* NULL section would let the same key be inserted twice.
|
|
32
|
+
*/
|
|
33
|
+
export class UserSettingBase extends AuditableEntity {
|
|
34
|
+
constructor() {
|
|
35
|
+
super(...arguments);
|
|
36
|
+
this.section = "default";
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
__decorate([
|
|
40
|
+
Property({ type: "varchar", length: 50, default: "default" }),
|
|
41
|
+
__metadata("design:type", Object)
|
|
42
|
+
], UserSettingBase.prototype, "section", void 0);
|
|
43
|
+
__decorate([
|
|
44
|
+
Property({ type: "varchar", length: 100 }),
|
|
45
|
+
__metadata("design:type", String)
|
|
46
|
+
], UserSettingBase.prototype, "key", void 0);
|
|
47
|
+
__decorate([
|
|
48
|
+
Property({ type: "jsonb", nullable: true }),
|
|
49
|
+
__metadata("design:type", Object)
|
|
50
|
+
], UserSettingBase.prototype, "value", void 0);
|
package/package.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@smounters/data",
|
|
3
|
+
"version": "2.3.0",
|
|
4
|
+
"description": "Reusable MikroORM entity fragments: UUIDv7 primary key, audit columns, per-user settings bag",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"mikro-orm",
|
|
7
|
+
"entity",
|
|
8
|
+
"postgres",
|
|
9
|
+
"uuidv7",
|
|
10
|
+
"typescript"
|
|
11
|
+
],
|
|
12
|
+
"license": "MIT",
|
|
13
|
+
"type": "module",
|
|
14
|
+
"exports": {
|
|
15
|
+
".": {
|
|
16
|
+
"types": "./dist/index.d.ts",
|
|
17
|
+
"import": "./dist/index.js"
|
|
18
|
+
}
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"dist",
|
|
22
|
+
"README.md",
|
|
23
|
+
"LICENSE",
|
|
24
|
+
"CHANGELOG.md"
|
|
25
|
+
],
|
|
26
|
+
"publishConfig": {
|
|
27
|
+
"access": "public"
|
|
28
|
+
},
|
|
29
|
+
"repository": {
|
|
30
|
+
"type": "git",
|
|
31
|
+
"url": "git+https://github.com/smounters/smounters-packages.git",
|
|
32
|
+
"directory": "packages/data"
|
|
33
|
+
},
|
|
34
|
+
"homepage": "https://smounters.github.io/smounters-packages/",
|
|
35
|
+
"engines": {
|
|
36
|
+
"node": ">=20.0.0"
|
|
37
|
+
},
|
|
38
|
+
"peerDependencies": {
|
|
39
|
+
"@mikro-orm/core": "^7",
|
|
40
|
+
"@mikro-orm/decorators": "^7"
|
|
41
|
+
},
|
|
42
|
+
"devDependencies": {
|
|
43
|
+
"@mikro-orm/core": "^7",
|
|
44
|
+
"@mikro-orm/decorators": "^7"
|
|
45
|
+
},
|
|
46
|
+
"scripts": {
|
|
47
|
+
"build": "tsc -p tsconfig.json",
|
|
48
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
49
|
+
"lint": "eslint \"src/**/*.ts\"",
|
|
50
|
+
"lint:fix": "eslint \"src/**/*.ts\" --fix",
|
|
51
|
+
"test": "vitest run --passWithNoTests",
|
|
52
|
+
"clean": "rm -rf dist"
|
|
53
|
+
}
|
|
54
|
+
}
|