@wrelik/db 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/CHANGELOG.md +12 -0
- package/package.json +21 -0
- package/src/index.ts +39 -0
- package/tsconfig.json +7 -0
package/CHANGELOG.md
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@wrelik/db",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"main": "./dist/index.js",
|
|
5
|
+
"types": "./dist/index.d.ts",
|
|
6
|
+
"dependencies": {
|
|
7
|
+
"@wrelik/errors": "0.1.0"
|
|
8
|
+
},
|
|
9
|
+
"devDependencies": {
|
|
10
|
+
"@types/node": "^25.2.0",
|
|
11
|
+
"tsup": "^8.0.1",
|
|
12
|
+
"vitest": "^1.2.2",
|
|
13
|
+
"@wrelik/eslint-config": "0.1.0",
|
|
14
|
+
"@wrelik/tsconfig": "0.1.0"
|
|
15
|
+
},
|
|
16
|
+
"scripts": {
|
|
17
|
+
"build": "tsup src/index.ts --format cjs,esm --dts --clean",
|
|
18
|
+
"lint": "eslint src/",
|
|
19
|
+
"test": "vitest run --passWithNoTests"
|
|
20
|
+
}
|
|
21
|
+
}
|
package/src/index.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { PermissionDeniedError, TenantRequiredError } from '@wrelik/errors';
|
|
2
|
+
|
|
3
|
+
// Helper types
|
|
4
|
+
type AccessChecker = (userId: string, tenantId: string) => Promise<boolean>;
|
|
5
|
+
|
|
6
|
+
let accessChecker: AccessChecker = async () => false; // Default deny
|
|
7
|
+
|
|
8
|
+
export function setTenantAccessChecker(checker: AccessChecker) {
|
|
9
|
+
accessChecker = checker;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export async function assertTenantAccess(userId: string, tenantId: string) {
|
|
13
|
+
if (!userId || !tenantId) {
|
|
14
|
+
throw new TenantRequiredError();
|
|
15
|
+
}
|
|
16
|
+
const allowed = await accessChecker(userId, tenantId);
|
|
17
|
+
if (!allowed) {
|
|
18
|
+
throw new PermissionDeniedError(`User ${userId} does not have access to tenant ${tenantId}`);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export function withTenant<T>(tenantId: string, fn: (tenantId: string) => Promise<T>): Promise<T> {
|
|
23
|
+
if (!tenantId) {
|
|
24
|
+
throw new TenantRequiredError();
|
|
25
|
+
}
|
|
26
|
+
return fn(tenantId);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// Singleton pattern for Prisma
|
|
30
|
+
export function getPrismaSingleton<T>(factory: () => T): T {
|
|
31
|
+
const globalForPrisma = global as unknown as { prisma: T };
|
|
32
|
+
const prisma = globalForPrisma.prisma || factory();
|
|
33
|
+
|
|
34
|
+
if (process.env.NODE_ENV !== 'production') {
|
|
35
|
+
globalForPrisma.prisma = prisma;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
return prisma;
|
|
39
|
+
}
|