authkit-api 0.0.0-stage → 1.0.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 +26 -0
- package/LICENSE +21 -0
- package/README.md +109 -2
- package/bin/cli.js +8 -0
- package/package.json +69 -4
- package/src/constants.js +24 -0
- package/src/generator.js +112 -0
- package/src/index.js +89 -0
- package/src/prompts.js +43 -0
- package/src/utils/fs.js +36 -0
- package/src/utils/logger.js +8 -0
- package/src/utils/packageJson.js +16 -0
- package/src/utils/validateProjectName.js +19 -0
- package/templates/base/Dockerfile +22 -0
- package/templates/base/README.md +108 -0
- package/templates/base/_dockerignore +16 -0
- package/templates/base/_env.example +25 -0
- package/templates/base/_gitignore +5 -0
- package/templates/base/_husky/pre-commit +1 -0
- package/templates/base/_prettierignore +5 -0
- package/templates/base/_prettierrc +1 -0
- package/templates/base/eslint.config.js +23 -0
- package/templates/base/package.json +62 -0
- package/templates/base/scripts/docker-entrypoint.sh +9 -0
- package/templates/base/scripts/generate-postman.js +70 -0
- package/templates/base/scripts/seed-admin.js +61 -0
- package/templates/base/src/app.js +46 -0
- package/templates/base/src/config/env.js +15 -0
- package/templates/base/src/config/env.schema.js +85 -0
- package/templates/base/src/config/logger.js +20 -0
- package/templates/base/src/constants/examples.js +3 -0
- package/templates/base/src/constants/roles.js +2 -0
- package/templates/base/src/constants/user.rules.js +16 -0
- package/templates/base/src/docs/openapi.js +26 -0
- package/templates/base/src/docs/openapi.registry.js +81 -0
- package/templates/base/src/docs/paths/auth.paths.js +87 -0
- package/templates/base/src/docs/paths/user.paths.js +87 -0
- package/templates/base/src/middlewares/authenticate.js +19 -0
- package/templates/base/src/middlewares/authorize.js +11 -0
- package/templates/base/src/middlewares/errorHandler.js +35 -0
- package/templates/base/src/middlewares/notFound.js +5 -0
- package/templates/base/src/middlewares/rateLimiter.js +20 -0
- package/templates/base/src/middlewares/validate.js +31 -0
- package/templates/base/src/modules/auth/auth.controller.js +40 -0
- package/templates/base/src/modules/auth/auth.cookie.js +21 -0
- package/templates/base/src/modules/auth/auth.routes.js +12 -0
- package/templates/base/src/modules/auth/auth.service.js +79 -0
- package/templates/base/src/modules/auth/auth.validation.js +41 -0
- package/templates/base/src/modules/user/user.controller.js +21 -0
- package/templates/base/src/modules/user/user.routes.js +22 -0
- package/templates/base/src/modules/user/user.service.js +19 -0
- package/templates/base/src/modules/user/user.validation.js +24 -0
- package/templates/base/src/routes/docs.routes.js +16 -0
- package/templates/base/src/routes/health.routes.js +17 -0
- package/templates/base/src/routes/index.js +13 -0
- package/templates/base/src/server.js +50 -0
- package/templates/base/src/utils/ApiError.js +32 -0
- package/templates/base/src/utils/apiResponse.js +8 -0
- package/templates/base/src/utils/password.js +14 -0
- package/templates/base/src/utils/token.js +46 -0
- package/templates/base/src/utils/zod.js +5 -0
- package/templates/base/tests/app.test.js +67 -0
- package/templates/base/tests/auth.test.js +185 -0
- package/templates/base/tests/authenticate.test.js +61 -0
- package/templates/base/tests/docs.test.js +115 -0
- package/templates/base/tests/env.test.js +94 -0
- package/templates/base/tests/health.test.js +21 -0
- package/templates/base/tests/helpers/auth.helper.js +41 -0
- package/templates/base/tests/password.test.js +18 -0
- package/templates/base/tests/postman.test.js +31 -0
- package/templates/base/tests/rateLimiter.test.js +27 -0
- package/templates/base/tests/seedAdmin.test.js +42 -0
- package/templates/base/tests/token.test.js +69 -0
- package/templates/base/tests/trustProxy.test.js +24 -0
- package/templates/base/tests/user.repository.test.js +210 -0
- package/templates/base/tests/user.test.js +144 -0
- package/templates/base/tests/validate.test.js +35 -0
- package/templates/base/tests/validation.test.js +61 -0
- package/templates/base/vitest.config.js +16 -0
- package/templates/databases/mongodb/README.part.md +23 -0
- package/templates/databases/mongodb/_github/workflows/ci.yml +29 -0
- package/templates/databases/mongodb/docker-compose.yml +30 -0
- package/templates/databases/mongodb/env.part +2 -0
- package/templates/databases/mongodb/package.part.json +4 -0
- package/templates/databases/mongodb/src/database/connection.js +39 -0
- package/templates/databases/mongodb/src/database/env.schema.js +3 -0
- package/templates/databases/mongodb/src/database/id.schema.js +3 -0
- package/templates/databases/mongodb/src/database/models/refreshToken.model.js +15 -0
- package/templates/databases/mongodb/src/database/models/user.model.js +41 -0
- package/templates/databases/mongodb/src/modules/user/user.repository.js +68 -0
- package/templates/databases/mongodb/tests/globalSetup.js +13 -0
- package/templates/databases/mongodb/tests/setup.js +17 -0
- package/templates/databases/postgres/README.part.md +31 -0
- package/templates/databases/postgres/_github/workflows/ci.yml +46 -0
- package/templates/databases/postgres/docker-compose.yml +34 -0
- package/templates/databases/postgres/env.part +2 -0
- package/templates/databases/postgres/package.part.json +15 -0
- package/templates/databases/postgres/prisma/migrations/20261030073256_init/migration.sql +39 -0
- package/templates/databases/postgres/prisma/migrations/migration_lock.toml +3 -0
- package/templates/databases/postgres/prisma/schema.prisma +39 -0
- package/templates/databases/postgres/prisma.config.js +14 -0
- package/templates/databases/postgres/src/database/connection.js +61 -0
- package/templates/databases/postgres/src/database/env.schema.js +3 -0
- package/templates/databases/postgres/src/database/id.schema.js +3 -0
- package/templates/databases/postgres/src/database/prisma.js +9 -0
- package/templates/databases/postgres/src/modules/user/user.repository.js +88 -0
- package/templates/databases/postgres/tests/connection.test.js +17 -0
- package/templates/databases/postgres/tests/globalSetup.js +60 -0
- package/templates/databases/postgres/tests/prismaSchema.test.js +27 -0
- package/templates/databases/postgres/tests/setup.js +15 -0
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
{
|
|
2
|
+
"scripts": {
|
|
3
|
+
"db:migrate": "prisma migrate dev",
|
|
4
|
+
"db:deploy": "prisma migrate deploy",
|
|
5
|
+
"db:generate": "prisma generate",
|
|
6
|
+
"db:studio": "prisma studio",
|
|
7
|
+
"postinstall": "prisma generate"
|
|
8
|
+
},
|
|
9
|
+
"dependencies": {
|
|
10
|
+
"@prisma/adapter-pg": "^7.10.1",
|
|
11
|
+
"@prisma/client": "^7.10.1",
|
|
12
|
+
"pg": "^8.16.3",
|
|
13
|
+
"prisma": "^7.10.1"
|
|
14
|
+
}
|
|
15
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
-- CreateEnum
|
|
2
|
+
CREATE TYPE "Role" AS ENUM ('user', 'admin');
|
|
3
|
+
|
|
4
|
+
-- CreateTable
|
|
5
|
+
CREATE TABLE "users" (
|
|
6
|
+
"id" UUID NOT NULL,
|
|
7
|
+
"name" VARCHAR(50) NOT NULL,
|
|
8
|
+
"email" VARCHAR(254) NOT NULL,
|
|
9
|
+
"password" TEXT NOT NULL,
|
|
10
|
+
"role" "Role" NOT NULL DEFAULT 'user',
|
|
11
|
+
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
12
|
+
"updatedAt" TIMESTAMP(3) NOT NULL,
|
|
13
|
+
|
|
14
|
+
CONSTRAINT "users_pkey" PRIMARY KEY ("id")
|
|
15
|
+
);
|
|
16
|
+
|
|
17
|
+
-- CreateTable
|
|
18
|
+
CREATE TABLE "refresh_tokens" (
|
|
19
|
+
"id" UUID NOT NULL,
|
|
20
|
+
"userId" UUID NOT NULL,
|
|
21
|
+
"tokenHash" CHAR(64) NOT NULL,
|
|
22
|
+
"expiresAt" TIMESTAMP(3) NOT NULL,
|
|
23
|
+
"revokedAt" TIMESTAMP(3),
|
|
24
|
+
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
|
25
|
+
|
|
26
|
+
CONSTRAINT "refresh_tokens_pkey" PRIMARY KEY ("id")
|
|
27
|
+
);
|
|
28
|
+
|
|
29
|
+
-- CreateIndex
|
|
30
|
+
CREATE UNIQUE INDEX "users_email_key" ON "users"("email");
|
|
31
|
+
|
|
32
|
+
-- CreateIndex
|
|
33
|
+
CREATE UNIQUE INDEX "refresh_tokens_tokenHash_key" ON "refresh_tokens"("tokenHash");
|
|
34
|
+
|
|
35
|
+
-- CreateIndex
|
|
36
|
+
CREATE INDEX "refresh_tokens_userId_idx" ON "refresh_tokens"("userId");
|
|
37
|
+
|
|
38
|
+
-- AddForeignKey
|
|
39
|
+
ALTER TABLE "refresh_tokens" ADD CONSTRAINT "refresh_tokens_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
generator client {
|
|
2
|
+
provider = "prisma-client"
|
|
3
|
+
output = "../src/generated/prisma"
|
|
4
|
+
}
|
|
5
|
+
|
|
6
|
+
datasource db {
|
|
7
|
+
provider = "postgresql"
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
enum Role {
|
|
11
|
+
user
|
|
12
|
+
admin
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
model User {
|
|
16
|
+
id String @id @default(uuid()) @db.Uuid
|
|
17
|
+
name String @db.VarChar(50)
|
|
18
|
+
email String @unique @db.VarChar(254)
|
|
19
|
+
password String
|
|
20
|
+
role Role @default(user)
|
|
21
|
+
createdAt DateTime @default(now())
|
|
22
|
+
updatedAt DateTime @updatedAt
|
|
23
|
+
refreshTokens RefreshToken[]
|
|
24
|
+
|
|
25
|
+
@@map("users")
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
model RefreshToken {
|
|
29
|
+
id String @id @default(uuid()) @db.Uuid
|
|
30
|
+
userId String @db.Uuid
|
|
31
|
+
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
|
32
|
+
tokenHash String @unique @db.Char(64)
|
|
33
|
+
expiresAt DateTime
|
|
34
|
+
revokedAt DateTime?
|
|
35
|
+
createdAt DateTime @default(now())
|
|
36
|
+
|
|
37
|
+
@@index([userId])
|
|
38
|
+
@@map("refresh_tokens")
|
|
39
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { defineConfig } from 'prisma/config';
|
|
2
|
+
|
|
3
|
+
// Prisma 7 no longer reads .env on its own, so load it here (a real environment variable wins).
|
|
4
|
+
try {
|
|
5
|
+
process.loadEnvFile('.env');
|
|
6
|
+
} catch {
|
|
7
|
+
// No .env file: DATABASE_URL must come from the environment.
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export default defineConfig({
|
|
11
|
+
schema: 'prisma/schema.prisma',
|
|
12
|
+
migrations: { path: 'prisma/migrations' },
|
|
13
|
+
datasource: { url: process.env.DATABASE_URL },
|
|
14
|
+
});
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { logger } from '../config/logger.js';
|
|
2
|
+
import { ApiError } from '../utils/ApiError.js';
|
|
3
|
+
import { prisma } from './prisma.js';
|
|
4
|
+
|
|
5
|
+
const HEALTH_TIMEOUT_MS = 1000;
|
|
6
|
+
|
|
7
|
+
export async function connectDatabase() {
|
|
8
|
+
await prisma.$connect();
|
|
9
|
+
await prisma.$queryRaw`SELECT 1`;
|
|
10
|
+
logger.info('Connected to PostgreSQL');
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export async function disconnectDatabase() {
|
|
14
|
+
await prisma.$disconnect();
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
// A live check: the pool reconnects on its own, so a flag set at startup would lie.
|
|
18
|
+
export async function isDatabaseConnected() {
|
|
19
|
+
let timer;
|
|
20
|
+
const timeout = new Promise((_resolve, reject) => {
|
|
21
|
+
timer = setTimeout(
|
|
22
|
+
() => reject(new Error('Database health check timed out')),
|
|
23
|
+
HEALTH_TIMEOUT_MS,
|
|
24
|
+
);
|
|
25
|
+
});
|
|
26
|
+
try {
|
|
27
|
+
await Promise.race([prisma.$queryRaw`SELECT 1`, timeout]);
|
|
28
|
+
return true;
|
|
29
|
+
} catch {
|
|
30
|
+
return false;
|
|
31
|
+
} finally {
|
|
32
|
+
clearTimeout(timer);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const INVALID_TEXT_REPRESENTATION = '22P02'; // Postgres: malformed uuid
|
|
37
|
+
|
|
38
|
+
// Turns Prisma errors into ApiErrors. Returns null for anything it does not know.
|
|
39
|
+
export function mapDatabaseError(err) {
|
|
40
|
+
const cause = err?.meta?.driverAdapterError?.cause;
|
|
41
|
+
switch (err?.code) {
|
|
42
|
+
case 'P2002': {
|
|
43
|
+
// The driver adapter reports the violated constraint, e.g. { index: 'users_email_key' }.
|
|
44
|
+
const target = err.meta?.target ?? Object.values(cause?.constraint ?? {});
|
|
45
|
+
const fields = [target].flat().map(String);
|
|
46
|
+
return fields.some((name) => name.includes('email'))
|
|
47
|
+
? ApiError.conflict('Email is already registered')
|
|
48
|
+
: ApiError.conflict('Resource already exists');
|
|
49
|
+
}
|
|
50
|
+
case 'P2025':
|
|
51
|
+
return ApiError.notFound();
|
|
52
|
+
case 'P2023':
|
|
53
|
+
return ApiError.badRequest('Invalid id');
|
|
54
|
+
case 'P2007':
|
|
55
|
+
return cause?.originalCode === INVALID_TEXT_REPRESENTATION
|
|
56
|
+
? ApiError.badRequest('Invalid id')
|
|
57
|
+
: null;
|
|
58
|
+
default:
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { PrismaPg } from '@prisma/adapter-pg';
|
|
2
|
+
import { env } from '../config/env.js';
|
|
3
|
+
// The generated client is TypeScript; importing it from JS relies on Node's built-in type stripping (Node >=22.18).
|
|
4
|
+
import { PrismaClient } from '../generated/prisma/client.ts';
|
|
5
|
+
|
|
6
|
+
// The one PrismaClient for the whole app.
|
|
7
|
+
export const prisma = new PrismaClient({
|
|
8
|
+
adapter: new PrismaPg({ connectionString: env.DATABASE_URL }),
|
|
9
|
+
});
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { prisma } from '../../database/prisma.js';
|
|
2
|
+
|
|
3
|
+
// Every query returns only these fields, so the password hash cannot leak by accident.
|
|
4
|
+
const publicUserSelect = {
|
|
5
|
+
id: true,
|
|
6
|
+
name: true,
|
|
7
|
+
email: true,
|
|
8
|
+
role: true,
|
|
9
|
+
createdAt: true,
|
|
10
|
+
updatedAt: true,
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export async function findById(id) {
|
|
14
|
+
return prisma.user.findUnique({ where: { id }, select: publicUserSelect });
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export async function findByEmail(email, { withPassword = false } = {}) {
|
|
18
|
+
return prisma.user.findUnique({
|
|
19
|
+
where: { email: email.trim().toLowerCase() },
|
|
20
|
+
select: withPassword ? { ...publicUserSelect, password: true } : publicUserSelect,
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function create({ name, email, password, role }) {
|
|
25
|
+
return prisma.user.create({
|
|
26
|
+
data: { name, email: email.trim().toLowerCase(), password, role },
|
|
27
|
+
select: publicUserSelect,
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export async function findMany({ page, limit }) {
|
|
32
|
+
const [users, total] = await prisma.$transaction([
|
|
33
|
+
prisma.user.findMany({
|
|
34
|
+
select: publicUserSelect,
|
|
35
|
+
orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
|
|
36
|
+
skip: (page - 1) * limit,
|
|
37
|
+
take: limit,
|
|
38
|
+
}),
|
|
39
|
+
prisma.user.count(),
|
|
40
|
+
]);
|
|
41
|
+
return { users, total };
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export async function updateRole(id, role) {
|
|
45
|
+
try {
|
|
46
|
+
return await prisma.user.update({ where: { id }, data: { role }, select: publicUserSelect });
|
|
47
|
+
} catch (err) {
|
|
48
|
+
if (err?.code === 'P2025') return null;
|
|
49
|
+
throw err;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// Refresh tokens are removed by the ON DELETE CASCADE foreign key.
|
|
54
|
+
export async function deleteById(id) {
|
|
55
|
+
try {
|
|
56
|
+
await prisma.user.delete({ where: { id } });
|
|
57
|
+
return true;
|
|
58
|
+
} catch (err) {
|
|
59
|
+
if (err?.code === 'P2025') return false;
|
|
60
|
+
throw err;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function saveRefreshToken({ userId, tokenHash, expiresAt }) {
|
|
65
|
+
await prisma.refreshToken.create({ data: { userId, tokenHash, expiresAt } });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export async function findRefreshToken(tokenHash) {
|
|
69
|
+
return prisma.refreshToken.findUnique({
|
|
70
|
+
where: { tokenHash },
|
|
71
|
+
select: { userId: true, expiresAt: true, revokedAt: true },
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function revokeRefreshToken(tokenHash) {
|
|
76
|
+
const { count } = await prisma.refreshToken.updateMany({
|
|
77
|
+
where: { tokenHash, revokedAt: null },
|
|
78
|
+
data: { revokedAt: new Date() },
|
|
79
|
+
});
|
|
80
|
+
return count > 0;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export async function revokeAllRefreshTokens(userId) {
|
|
84
|
+
await prisma.refreshToken.updateMany({
|
|
85
|
+
where: { userId, revokedAt: null },
|
|
86
|
+
data: { revokedAt: new Date() },
|
|
87
|
+
});
|
|
88
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { isDatabaseConnected } from '../src/database/connection.js';
|
|
3
|
+
import { prisma } from '../src/database/prisma.js';
|
|
4
|
+
|
|
5
|
+
describe('isDatabaseConnected (postgres)', () => {
|
|
6
|
+
afterEach(() => vi.restoreAllMocks());
|
|
7
|
+
|
|
8
|
+
it('is false when the query fails', async () => {
|
|
9
|
+
vi.spyOn(prisma, '$queryRaw').mockRejectedValue(new Error('connection lost'));
|
|
10
|
+
expect(await isDatabaseConnected()).toBe(false);
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
it('is false when the database does not answer in time', async () => {
|
|
14
|
+
vi.spyOn(prisma, '$queryRaw').mockReturnValue(new Promise(() => {}));
|
|
15
|
+
expect(await isDatabaseConnected()).toBe(false);
|
|
16
|
+
});
|
|
17
|
+
});
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { execSync } from 'node:child_process';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { parseEnv } from 'node:util';
|
|
4
|
+
import pg from 'pg';
|
|
5
|
+
|
|
6
|
+
const DEFAULT_URL = 'postgresql://postgres:postgres@localhost:5432/app';
|
|
7
|
+
const ENV_FILE = new URL('../.env', import.meta.url);
|
|
8
|
+
const NOT_RUNNING_MESSAGE = `Cannot reach Postgres. Start it first: docker compose up -d --wait db
|
|
9
|
+
(or set DATABASE_URL to a running server).`;
|
|
10
|
+
|
|
11
|
+
// A real environment variable wins, then DATABASE_URL from .env. Only that one
|
|
12
|
+
// variable is read, so the rest of .env cannot change the test setup.
|
|
13
|
+
function databaseUrl() {
|
|
14
|
+
if (process.env.DATABASE_URL) return process.env.DATABASE_URL;
|
|
15
|
+
if (existsSync(ENV_FILE)) {
|
|
16
|
+
const fromFile = parseEnv(readFileSync(ENV_FILE, 'utf8')).DATABASE_URL;
|
|
17
|
+
if (fromFile) return fromFile;
|
|
18
|
+
}
|
|
19
|
+
return DEFAULT_URL;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function exitNotRunning() {
|
|
23
|
+
console.error(NOT_RUNNING_MESSAGE);
|
|
24
|
+
process.exit(1);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// Creates `<db>_test` on the same server if needed, points DATABASE_URL at it, and applies migrations.
|
|
28
|
+
export async function setup() {
|
|
29
|
+
const url = new URL(databaseUrl());
|
|
30
|
+
const testDatabase = `${url.pathname.slice(1).replace(/_test$/, '')}_test`;
|
|
31
|
+
|
|
32
|
+
const admin = new URL(url);
|
|
33
|
+
admin.pathname = '/postgres';
|
|
34
|
+
const client = new pg.Client({ connectionString: admin.toString() });
|
|
35
|
+
try {
|
|
36
|
+
await client.connect();
|
|
37
|
+
const { rowCount } = await client.query('SELECT 1 FROM pg_database WHERE datname = $1', [
|
|
38
|
+
testDatabase,
|
|
39
|
+
]);
|
|
40
|
+
if (rowCount === 0) await client.query(`CREATE DATABASE "${testDatabase}"`);
|
|
41
|
+
} catch (err) {
|
|
42
|
+
if (err?.code === 'ECONNREFUSED' || err?.code === 'ENOTFOUND' || err?.code === 'ETIMEDOUT') {
|
|
43
|
+
exitNotRunning();
|
|
44
|
+
}
|
|
45
|
+
if (err instanceof AggregateError) exitNotRunning();
|
|
46
|
+
throw err;
|
|
47
|
+
} finally {
|
|
48
|
+
await client.end().catch(() => {});
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
url.pathname = `/${testDatabase}`;
|
|
52
|
+
process.env.DATABASE_URL = url.toString();
|
|
53
|
+
execSync('npx prisma migrate deploy', {
|
|
54
|
+
stdio: 'pipe',
|
|
55
|
+
env: process.env,
|
|
56
|
+
cwd: new URL('..', import.meta.url),
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function teardown() {}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { describe, expect, it } from 'vitest';
|
|
3
|
+
import { ROLE_VALUES } from '../src/constants/roles.js';
|
|
4
|
+
import { USER_RULES } from '../src/constants/user.rules.js';
|
|
5
|
+
|
|
6
|
+
// Prisma's schema cannot import JS, so this guards against the limits drifting apart.
|
|
7
|
+
const schema = readFileSync(new URL('../prisma/schema.prisma', import.meta.url), 'utf8');
|
|
8
|
+
|
|
9
|
+
describe('prisma schema', () => {
|
|
10
|
+
it('uses the name length from user.rules.js', () => {
|
|
11
|
+
expect(schema).toMatch(
|
|
12
|
+
new RegExp(String.raw`\bname\s+String\s+@db\.VarChar\(${USER_RULES.NAME.MAX}\)`),
|
|
13
|
+
);
|
|
14
|
+
});
|
|
15
|
+
|
|
16
|
+
it('uses the email length from user.rules.js and makes it unique', () => {
|
|
17
|
+
expect(schema).toMatch(
|
|
18
|
+
new RegExp(String.raw`\bemail\s+String\s+@unique\s+@db\.VarChar\(${USER_RULES.EMAIL.MAX}\)`),
|
|
19
|
+
);
|
|
20
|
+
});
|
|
21
|
+
|
|
22
|
+
it('has a Role enum equal to ROLE_VALUES', () => {
|
|
23
|
+
const body = schema.match(/enum\s+Role\s*\{([^}]*)\}/)?.[1] ?? '';
|
|
24
|
+
const values = body.split(/\s+/).filter(Boolean);
|
|
25
|
+
expect(values).toEqual([...ROLE_VALUES]);
|
|
26
|
+
});
|
|
27
|
+
});
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { afterAll, afterEach, beforeAll } from 'vitest';
|
|
2
|
+
import { connectDatabase, disconnectDatabase } from '../src/database/connection.js';
|
|
3
|
+
import { prisma } from '../src/database/prisma.js';
|
|
4
|
+
|
|
5
|
+
beforeAll(async () => {
|
|
6
|
+
await connectDatabase();
|
|
7
|
+
});
|
|
8
|
+
|
|
9
|
+
afterEach(async () => {
|
|
10
|
+
await prisma.$executeRawUnsafe('TRUNCATE users, refresh_tokens CASCADE');
|
|
11
|
+
});
|
|
12
|
+
|
|
13
|
+
afterAll(async () => {
|
|
14
|
+
await disconnectDatabase();
|
|
15
|
+
});
|