authkit-api 0.0.0-stage → 1.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.
Files changed (210) hide show
  1. package/CHANGELOG.md +35 -0
  2. package/LICENSE +21 -0
  3. package/README.md +125 -2
  4. package/bin/cli.js +8 -0
  5. package/package.json +76 -4
  6. package/src/constants.js +29 -0
  7. package/src/generator.js +142 -0
  8. package/src/index.js +99 -0
  9. package/src/prompts.js +59 -0
  10. package/src/utils/fs.js +36 -0
  11. package/src/utils/logger.js +8 -0
  12. package/src/utils/packageJson.js +16 -0
  13. package/src/utils/validateProjectName.js +19 -0
  14. package/templates/base/Dockerfile +22 -0
  15. package/templates/base/README.md +108 -0
  16. package/templates/base/_dockerignore +16 -0
  17. package/templates/base/_env.example +25 -0
  18. package/templates/base/_gitignore +5 -0
  19. package/templates/base/_husky/pre-commit +1 -0
  20. package/templates/base/_prettierignore +5 -0
  21. package/templates/base/_prettierrc +1 -0
  22. package/templates/base/package.json +62 -0
  23. package/templates/base/scripts/docker-entrypoint.sh +9 -0
  24. package/templates/base/scripts/generate-postman.ts +102 -0
  25. package/templates/base/scripts/seed-admin.ts +62 -0
  26. package/templates/base/src/app.ts +46 -0
  27. package/templates/base/src/config/env.schema.ts +85 -0
  28. package/templates/base/src/config/env.ts +15 -0
  29. package/templates/base/src/config/logger.ts +20 -0
  30. package/templates/base/src/constants/examples.ts +3 -0
  31. package/templates/base/src/constants/roles.ts +4 -0
  32. package/templates/base/src/constants/user.rules.ts +16 -0
  33. package/templates/base/src/docs/openapi.registry.ts +90 -0
  34. package/templates/base/src/docs/openapi.ts +36 -0
  35. package/templates/base/src/docs/paths/auth.paths.ts +88 -0
  36. package/templates/base/src/docs/paths/user.paths.ts +88 -0
  37. package/templates/base/src/middlewares/authenticate.ts +20 -0
  38. package/templates/base/src/middlewares/authorize.ts +13 -0
  39. package/templates/base/src/middlewares/errorHandler.ts +52 -0
  40. package/templates/base/src/middlewares/notFound.ts +6 -0
  41. package/templates/base/src/middlewares/rateLimiter.ts +20 -0
  42. package/templates/base/src/middlewares/validate.ts +39 -0
  43. package/templates/base/src/modules/auth/auth.controller.ts +45 -0
  44. package/templates/base/src/modules/auth/auth.cookie.ts +22 -0
  45. package/templates/base/src/modules/auth/auth.routes.ts +12 -0
  46. package/templates/base/src/modules/auth/auth.service.ts +81 -0
  47. package/templates/base/src/modules/auth/auth.validation.ts +44 -0
  48. package/templates/base/src/modules/user/user.controller.ts +24 -0
  49. package/templates/base/src/modules/user/user.routes.ts +22 -0
  50. package/templates/base/src/modules/user/user.service.ts +57 -0
  51. package/templates/base/src/modules/user/user.validation.ts +27 -0
  52. package/templates/base/src/routes/docs.routes.ts +16 -0
  53. package/templates/base/src/routes/health.routes.ts +17 -0
  54. package/templates/base/src/routes/index.ts +13 -0
  55. package/templates/base/src/server.ts +51 -0
  56. package/templates/base/src/types/express.d.ts +14 -0
  57. package/templates/base/src/utils/ApiError.ts +35 -0
  58. package/templates/base/src/utils/apiResponse.ts +24 -0
  59. package/templates/base/src/utils/password.ts +14 -0
  60. package/templates/base/src/utils/token.ts +60 -0
  61. package/templates/base/src/utils/zod.ts +5 -0
  62. package/templates/base/tests/app.test.ts +67 -0
  63. package/templates/base/tests/auth.test.ts +194 -0
  64. package/templates/base/tests/authenticate.test.ts +61 -0
  65. package/templates/base/tests/docs.test.ts +127 -0
  66. package/templates/base/tests/env.test.ts +96 -0
  67. package/templates/base/tests/health.test.ts +21 -0
  68. package/templates/base/tests/helpers/auth.helper.ts +49 -0
  69. package/templates/base/tests/password.test.ts +18 -0
  70. package/templates/base/tests/postman.test.ts +32 -0
  71. package/templates/base/tests/rateLimiter.test.ts +27 -0
  72. package/templates/base/tests/seedAdmin.test.ts +42 -0
  73. package/templates/base/tests/token.test.ts +69 -0
  74. package/templates/base/tests/trustProxy.test.ts +24 -0
  75. package/templates/base/tests/user.repository.test.ts +211 -0
  76. package/templates/base/tests/user.test.ts +145 -0
  77. package/templates/base/tests/validate.test.ts +42 -0
  78. package/templates/base/tests/validation.test.ts +62 -0
  79. package/templates/base/vitest.config.ts +16 -0
  80. package/templates/databases/mongodb/README.part.md +23 -0
  81. package/templates/databases/mongodb/_github/workflows/ci.yml +29 -0
  82. package/templates/databases/mongodb/docker-compose.yml +30 -0
  83. package/templates/databases/mongodb/env.part +2 -0
  84. package/templates/databases/mongodb/package.part.json +4 -0
  85. package/templates/databases/mongodb/src/database/connection.ts +46 -0
  86. package/templates/databases/mongodb/src/database/env.schema.ts +3 -0
  87. package/templates/databases/mongodb/src/database/id.schema.ts +3 -0
  88. package/templates/databases/mongodb/src/database/models/refreshToken.model.ts +24 -0
  89. package/templates/databases/mongodb/src/database/models/user.model.ts +52 -0
  90. package/templates/databases/mongodb/src/modules/user/user.repository.ts +91 -0
  91. package/templates/databases/mongodb/tests/globalSetup.ts +13 -0
  92. package/templates/databases/mongodb/tests/setup.ts +17 -0
  93. package/templates/databases/postgres/README.part.md +31 -0
  94. package/templates/databases/postgres/_github/workflows/ci.yml +46 -0
  95. package/templates/databases/postgres/docker-compose.yml +34 -0
  96. package/templates/databases/postgres/env.part +2 -0
  97. package/templates/databases/postgres/package.part.json +15 -0
  98. package/templates/databases/postgres/prisma/migrations/20261030073256_init/migration.sql +39 -0
  99. package/templates/databases/postgres/prisma/migrations/migration_lock.toml +3 -0
  100. package/templates/databases/postgres/prisma/schema.prisma +39 -0
  101. package/templates/databases/postgres/prisma.config.ts +14 -0
  102. package/templates/databases/postgres/src/database/connection.ts +72 -0
  103. package/templates/databases/postgres/src/database/env.schema.ts +3 -0
  104. package/templates/databases/postgres/src/database/id.schema.ts +3 -0
  105. package/templates/databases/postgres/src/database/prisma.ts +9 -0
  106. package/templates/databases/postgres/src/modules/user/user.repository.ts +111 -0
  107. package/templates/databases/postgres/tests/connection.test.ts +19 -0
  108. package/templates/databases/postgres/tests/globalSetup.ts +66 -0
  109. package/templates/databases/postgres/tests/prismaSchema.test.ts +27 -0
  110. package/templates/databases/postgres/tests/setup.ts +15 -0
  111. package/templates/languages/js/eslint.config.js +23 -0
  112. package/templates/languages/ts/eslint.config.js +30 -0
  113. package/templates/languages/ts/package.part.json +21 -0
  114. package/templates/languages/ts/tsconfig.json +15 -0
  115. package/templates-js/base/Dockerfile +22 -0
  116. package/templates-js/base/README.md +108 -0
  117. package/templates-js/base/_dockerignore +16 -0
  118. package/templates-js/base/_env.example +25 -0
  119. package/templates-js/base/_gitignore +5 -0
  120. package/templates-js/base/_husky/pre-commit +1 -0
  121. package/templates-js/base/_prettierignore +5 -0
  122. package/templates-js/base/_prettierrc +1 -0
  123. package/templates-js/base/package.json +62 -0
  124. package/templates-js/base/scripts/docker-entrypoint.sh +9 -0
  125. package/templates-js/base/scripts/generate-postman.js +70 -0
  126. package/templates-js/base/scripts/seed-admin.js +61 -0
  127. package/templates-js/base/src/app.js +46 -0
  128. package/templates-js/base/src/config/env.js +15 -0
  129. package/templates-js/base/src/config/env.schema.js +85 -0
  130. package/templates-js/base/src/config/logger.js +20 -0
  131. package/templates-js/base/src/constants/examples.js +3 -0
  132. package/templates-js/base/src/constants/roles.js +2 -0
  133. package/templates-js/base/src/constants/user.rules.js +16 -0
  134. package/templates-js/base/src/docs/openapi.js +26 -0
  135. package/templates-js/base/src/docs/openapi.registry.js +81 -0
  136. package/templates-js/base/src/docs/paths/auth.paths.js +87 -0
  137. package/templates-js/base/src/docs/paths/user.paths.js +87 -0
  138. package/templates-js/base/src/middlewares/authenticate.js +19 -0
  139. package/templates-js/base/src/middlewares/authorize.js +11 -0
  140. package/templates-js/base/src/middlewares/errorHandler.js +35 -0
  141. package/templates-js/base/src/middlewares/notFound.js +5 -0
  142. package/templates-js/base/src/middlewares/rateLimiter.js +20 -0
  143. package/templates-js/base/src/middlewares/validate.js +31 -0
  144. package/templates-js/base/src/modules/auth/auth.controller.js +40 -0
  145. package/templates-js/base/src/modules/auth/auth.cookie.js +21 -0
  146. package/templates-js/base/src/modules/auth/auth.routes.js +12 -0
  147. package/templates-js/base/src/modules/auth/auth.service.js +79 -0
  148. package/templates-js/base/src/modules/auth/auth.validation.js +41 -0
  149. package/templates-js/base/src/modules/user/user.controller.js +21 -0
  150. package/templates-js/base/src/modules/user/user.routes.js +22 -0
  151. package/templates-js/base/src/modules/user/user.service.js +19 -0
  152. package/templates-js/base/src/modules/user/user.validation.js +24 -0
  153. package/templates-js/base/src/routes/docs.routes.js +16 -0
  154. package/templates-js/base/src/routes/health.routes.js +17 -0
  155. package/templates-js/base/src/routes/index.js +13 -0
  156. package/templates-js/base/src/server.js +50 -0
  157. package/templates-js/base/src/utils/ApiError.js +32 -0
  158. package/templates-js/base/src/utils/apiResponse.js +8 -0
  159. package/templates-js/base/src/utils/password.js +14 -0
  160. package/templates-js/base/src/utils/token.js +46 -0
  161. package/templates-js/base/src/utils/zod.js +5 -0
  162. package/templates-js/base/tests/app.test.js +67 -0
  163. package/templates-js/base/tests/auth.test.js +185 -0
  164. package/templates-js/base/tests/authenticate.test.js +61 -0
  165. package/templates-js/base/tests/docs.test.js +115 -0
  166. package/templates-js/base/tests/env.test.js +94 -0
  167. package/templates-js/base/tests/health.test.js +21 -0
  168. package/templates-js/base/tests/helpers/auth.helper.js +41 -0
  169. package/templates-js/base/tests/password.test.js +18 -0
  170. package/templates-js/base/tests/postman.test.js +31 -0
  171. package/templates-js/base/tests/rateLimiter.test.js +27 -0
  172. package/templates-js/base/tests/seedAdmin.test.js +42 -0
  173. package/templates-js/base/tests/token.test.js +69 -0
  174. package/templates-js/base/tests/trustProxy.test.js +24 -0
  175. package/templates-js/base/tests/user.repository.test.js +210 -0
  176. package/templates-js/base/tests/user.test.js +144 -0
  177. package/templates-js/base/tests/validate.test.js +35 -0
  178. package/templates-js/base/tests/validation.test.js +61 -0
  179. package/templates-js/base/vitest.config.js +16 -0
  180. package/templates-js/databases/mongodb/README.part.md +23 -0
  181. package/templates-js/databases/mongodb/_github/workflows/ci.yml +29 -0
  182. package/templates-js/databases/mongodb/docker-compose.yml +30 -0
  183. package/templates-js/databases/mongodb/env.part +2 -0
  184. package/templates-js/databases/mongodb/package.part.json +4 -0
  185. package/templates-js/databases/mongodb/src/database/connection.js +39 -0
  186. package/templates-js/databases/mongodb/src/database/env.schema.js +3 -0
  187. package/templates-js/databases/mongodb/src/database/id.schema.js +3 -0
  188. package/templates-js/databases/mongodb/src/database/models/refreshToken.model.js +15 -0
  189. package/templates-js/databases/mongodb/src/database/models/user.model.js +41 -0
  190. package/templates-js/databases/mongodb/src/modules/user/user.repository.js +68 -0
  191. package/templates-js/databases/mongodb/tests/globalSetup.js +13 -0
  192. package/templates-js/databases/mongodb/tests/setup.js +17 -0
  193. package/templates-js/databases/postgres/README.part.md +31 -0
  194. package/templates-js/databases/postgres/_github/workflows/ci.yml +46 -0
  195. package/templates-js/databases/postgres/docker-compose.yml +34 -0
  196. package/templates-js/databases/postgres/env.part +2 -0
  197. package/templates-js/databases/postgres/package.part.json +15 -0
  198. package/templates-js/databases/postgres/prisma/migrations/20261030073256_init/migration.sql +39 -0
  199. package/templates-js/databases/postgres/prisma/migrations/migration_lock.toml +3 -0
  200. package/templates-js/databases/postgres/prisma/schema.prisma +39 -0
  201. package/templates-js/databases/postgres/prisma.config.js +14 -0
  202. package/templates-js/databases/postgres/src/database/connection.js +61 -0
  203. package/templates-js/databases/postgres/src/database/env.schema.js +3 -0
  204. package/templates-js/databases/postgres/src/database/id.schema.js +3 -0
  205. package/templates-js/databases/postgres/src/database/prisma.js +9 -0
  206. package/templates-js/databases/postgres/src/modules/user/user.repository.js +88 -0
  207. package/templates-js/databases/postgres/tests/connection.test.js +17 -0
  208. package/templates-js/databases/postgres/tests/globalSetup.js +60 -0
  209. package/templates-js/databases/postgres/tests/prismaSchema.test.js +27 -0
  210. package/templates-js/databases/postgres/tests/setup.js +15 -0
@@ -0,0 +1,52 @@
1
+ import mongoose from 'mongoose';
2
+ import { ROLE_VALUES, ROLES } from '../../constants/roles.ts';
3
+ import { USER_RULES } from '../../constants/user.rules.ts';
4
+ import type { HydratedDocument, InferSchemaType, Types } from 'mongoose';
5
+
6
+ const userSchema = new mongoose.Schema(
7
+ {
8
+ name: {
9
+ type: String,
10
+ required: true,
11
+ trim: true,
12
+ minlength: USER_RULES.NAME.MIN,
13
+ maxlength: USER_RULES.NAME.MAX,
14
+ },
15
+ email: {
16
+ type: String,
17
+ required: true,
18
+ unique: true,
19
+ lowercase: true,
20
+ trim: true,
21
+ maxlength: USER_RULES.EMAIL.MAX,
22
+ },
23
+ // Select: false keeps the hash out of every query unless asked for.
24
+ password: { type: String, required: true, select: false },
25
+ role: { type: String, enum: ROLE_VALUES, default: ROLES.USER },
26
+ },
27
+ { timestamps: true },
28
+ );
29
+
30
+ interface UserJson {
31
+ // The plain object Mongoose hands to the transform, reshaped in place into a public user.
32
+ _id?: Types.ObjectId;
33
+ __v?: number;
34
+ password?: string;
35
+ id?: string;
36
+ }
37
+
38
+ // The only shape a user ever leaves the database layer in.
39
+ function toPublic(_doc: unknown, ret: UserJson) {
40
+ ret.id = ret._id!.toString();
41
+ delete ret._id;
42
+ delete ret.__v;
43
+ delete ret.password;
44
+ return ret;
45
+ }
46
+
47
+ userSchema.set('toJSON', { transform: toPublic });
48
+ userSchema.set('toObject', { transform: toPublic });
49
+
50
+ export const User = mongoose.model('User', userSchema);
51
+
52
+ export type UserDocument = HydratedDocument<InferSchemaType<typeof userSchema>>;
@@ -0,0 +1,91 @@
1
+ import { RefreshToken } from '../../database/models/refreshToken.model.ts';
2
+ import { User } from '../../database/models/user.model.ts';
3
+ import type { Role } from '../../constants/roles.ts';
4
+ import type { UserDocument } from '../../database/models/user.model.ts';
5
+ import type { PublicUser } from '../../docs/openapi.registry.ts';
6
+ import type { UserRepository, UserWithPassword } from './user.service.ts';
7
+
8
+ type CreateUserInput = Parameters<UserRepository['create']>[0];
9
+
10
+ // The one place a Mongoose document becomes a plain public user.
11
+ const toPublicUser = <T extends UserDocument | null>(doc: T) =>
12
+ (doc ? doc.toJSON() : null) as T extends UserDocument ? PublicUser : null;
13
+
14
+ export async function findById(id: string) {
15
+ return toPublicUser(await User.findById(id));
16
+ }
17
+
18
+ export function findByEmail(
19
+ email: string,
20
+ options?: { withPassword?: false },
21
+ ): Promise<PublicUser | null>;
22
+ export function findByEmail(
23
+ email: string,
24
+ options: { withPassword: true },
25
+ ): Promise<UserWithPassword | null>;
26
+ export async function findByEmail(email: string, { withPassword = false } = {}) {
27
+ const query = User.findOne({ email: email.trim().toLowerCase() });
28
+ if (withPassword) query.select('+password');
29
+ const doc = await query;
30
+ if (!doc) return null;
31
+ const user = toPublicUser(doc);
32
+ return withPassword ? { ...user, password: doc.password } : user;
33
+ }
34
+
35
+ export async function create({ name, email, password, role }: CreateUserInput) {
36
+ return toPublicUser(await User.create({ name, email, password, role }));
37
+ }
38
+
39
+ export async function findMany({ page, limit }: { page: number; limit: number }) {
40
+ const [docs, total] = await Promise.all([
41
+ User.find()
42
+ .sort({ createdAt: -1, _id: -1 })
43
+ .skip((page - 1) * limit)
44
+ .limit(limit),
45
+ User.countDocuments(),
46
+ ]);
47
+ return { users: docs.map(toPublicUser), total };
48
+ }
49
+
50
+ export async function updateRole(id: string, role: Role) {
51
+ return toPublicUser(
52
+ await User.findByIdAndUpdate(id, { role }, { runValidators: true, returnDocument: 'after' }),
53
+ );
54
+ }
55
+
56
+ export async function deleteById(id: string) {
57
+ const deleted = await User.findByIdAndDelete(id);
58
+ if (!deleted) return false;
59
+ await RefreshToken.deleteMany({ userId: id });
60
+ return true;
61
+ }
62
+
63
+ export async function saveRefreshToken({
64
+ userId,
65
+ tokenHash,
66
+ expiresAt,
67
+ }: {
68
+ userId: string;
69
+ tokenHash: string;
70
+ expiresAt: Date;
71
+ }) {
72
+ await RefreshToken.create({ userId, tokenHash, expiresAt });
73
+ }
74
+
75
+ export async function findRefreshToken(tokenHash: string) {
76
+ const doc = await RefreshToken.findOne({ tokenHash });
77
+ if (!doc) return null;
78
+ return { userId: doc.userId.toString(), expiresAt: doc.expiresAt, revokedAt: doc.revokedAt };
79
+ }
80
+
81
+ export async function revokeRefreshToken(tokenHash: string) {
82
+ const result = await RefreshToken.updateOne(
83
+ { tokenHash, revokedAt: null },
84
+ { revokedAt: new Date() },
85
+ );
86
+ return result.modifiedCount > 0;
87
+ }
88
+
89
+ export async function revokeAllRefreshTokens(userId: string) {
90
+ await RefreshToken.updateMany({ userId, revokedAt: null }, { revokedAt: new Date() });
91
+ }
@@ -0,0 +1,13 @@
1
+ import { MongoMemoryServer } from 'mongodb-memory-server';
2
+
3
+ let mongoServer: MongoMemoryServer | undefined;
4
+
5
+ // Starts one in-memory MongoDB for the whole test run, so no local MongoDB is needed.
6
+ export async function setup() {
7
+ mongoServer = await MongoMemoryServer.create();
8
+ process.env.MONGODB_URI = mongoServer.getUri('test');
9
+ }
10
+
11
+ export async function teardown() {
12
+ await mongoServer?.stop();
13
+ }
@@ -0,0 +1,17 @@
1
+ import mongoose from 'mongoose';
2
+ import { afterAll, afterEach, beforeAll } from 'vitest';
3
+ import { connectDatabase, disconnectDatabase } from '../src/database/connection.ts';
4
+
5
+ beforeAll(async () => {
6
+ await connectDatabase();
7
+ // Build the unique indexes before the first test so duplicate checks are reliable.
8
+ await Promise.all(Object.values(mongoose.models).map((model) => model.syncIndexes()));
9
+ });
10
+
11
+ afterEach(async () => {
12
+ await Promise.all(Object.values(mongoose.connection.collections).map((c) => c.deleteMany({})));
13
+ });
14
+
15
+ afterAll(async () => {
16
+ await disconnectDatabase();
17
+ });
@@ -0,0 +1,31 @@
1
+ ## Quick start
2
+
3
+ ```bash
4
+ cd {{projectName}}
5
+ cp .env.example .env
6
+ npm install
7
+ docker compose up -d --wait db
8
+ npm run db:deploy
9
+ npm run dev
10
+ ```
11
+
12
+ The API is on <http://localhost:3000>. `npm test` needs the same running server: it takes `DATABASE_URL` from the environment, else from `.env` (else `postgresql://postgres:postgres@localhost:5432/app`), and creates and migrates a separate `<database>_test` database for itself.
13
+
14
+ ## Database
15
+
16
+ PostgreSQL with Prisma. The generated client lives in `src/generated/prisma` and is rebuilt by `npm install` and `npm run db:generate`.
17
+
18
+ | Variable | Meaning |
19
+ | -------------- | ---------------------------------- |
20
+ | `DATABASE_URL` | Connection string of your Postgres |
21
+
22
+ | Script | Does |
23
+ | --------------------- | ------------------------------------------ |
24
+ | `npm run db:migrate` | Create and apply a migration (development) |
25
+ | `npm run db:deploy` | Apply existing migrations |
26
+ | `npm run db:generate` | Regenerate the Prisma client |
27
+ | `npm run db:studio` | Open Prisma Studio |
28
+
29
+ **Docker port.** The compose database is published on host port `5432`. If you already run Postgres there, pick another port, for example `POSTGRES_PORT=5433`: set it when you run `docker compose up -d --wait db` or `npm run docker:up`, and put the same port in `DATABASE_URL` in `.env` (tests read it too). In Docker, the container applies migrations itself on start.
30
+
31
+ **Adding a user field.** Add the column to `model User` in `prisma/schema.prisma`, run `npm run db:migrate -- --name add_phone`, then add the field to `publicUserSelect` and to `create` in `src/modules/user/user.repository.ts`.
@@ -0,0 +1,46 @@
1
+ name: CI
2
+
3
+ on: [push, pull_request]
4
+
5
+ jobs:
6
+ test:
7
+ runs-on: ubuntu-latest
8
+ services:
9
+ postgres:
10
+ image: postgres:17-alpine
11
+ env:
12
+ POSTGRES_USER: postgres
13
+ POSTGRES_PASSWORD: postgres
14
+ POSTGRES_DB: app
15
+ ports:
16
+ - 5432:5432
17
+ options: >-
18
+ --health-cmd "pg_isready -U postgres"
19
+ --health-interval 5s
20
+ --health-timeout 5s
21
+ --health-retries 10
22
+ env:
23
+ DATABASE_URL: postgresql://postgres:postgres@localhost:5432/app
24
+ steps:
25
+ - uses: actions/checkout@v7
26
+ - uses: actions/setup-node@v7
27
+ with:
28
+ node-version: 24
29
+ cache: npm
30
+ - run: npm ci
31
+ - run: npm run lint
32
+ - run: npm run format:check
33
+ - run: npm run db:deploy
34
+ - run: npm test
35
+
36
+ docker:
37
+ needs: test
38
+ runs-on: ubuntu-latest
39
+ steps:
40
+ - uses: actions/checkout@v7
41
+ - uses: docker/setup-buildx-action@v4
42
+ - uses: docker/build-push-action@v7
43
+ with:
44
+ context: .
45
+ push: false
46
+ tags: app:ci
@@ -0,0 +1,34 @@
1
+ name: '{{projectName}}'
2
+
3
+ services:
4
+ app:
5
+ build: .
6
+ env_file: .env
7
+ environment:
8
+ NODE_ENV: production
9
+ PORT: 3000
10
+ DATABASE_URL: postgresql://postgres:postgres@db:5432/{{databaseName}}
11
+ depends_on:
12
+ db:
13
+ condition: service_healthy
14
+ ports:
15
+ - '${PORT:-3000}:3000'
16
+
17
+ db:
18
+ image: postgres:17-alpine
19
+ environment:
20
+ POSTGRES_USER: postgres
21
+ POSTGRES_PASSWORD: postgres
22
+ POSTGRES_DB: '{{databaseName}}'
23
+ ports:
24
+ - '${POSTGRES_PORT:-5432}:5432'
25
+ volumes:
26
+ - pgdata:/var/lib/postgresql/data
27
+ healthcheck:
28
+ test: ['CMD-SHELL', 'pg_isready -U postgres']
29
+ interval: 5s
30
+ timeout: 5s
31
+ retries: 10
32
+
33
+ volumes:
34
+ pgdata:
@@ -0,0 +1,2 @@
1
+ # --- database ---
2
+ DATABASE_URL=postgresql://postgres:postgres@localhost:5432/{{databaseName}}
@@ -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,3 @@
1
+ # Please do not edit this file manually
2
+ # It should be added in your version-control system (e.g., Git)
3
+ provider = "postgresql"
@@ -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,72 @@
1
+ import { logger } from '../config/logger.ts';
2
+ import { ApiError } from '../utils/ApiError.ts';
3
+ import { prisma } from './prisma.ts';
4
+
5
+ const HEALTH_TIMEOUT_MS = 1000;
6
+
7
+ interface PrismaError extends Partial<Error> {
8
+ // Anything can reach the error handler. These are the fields read from a Prisma error.
9
+ code?: unknown;
10
+ meta?: {
11
+ target?: unknown;
12
+ driverAdapterError?: {
13
+ cause?: { constraint?: Record<string, unknown>; originalCode?: string };
14
+ };
15
+ };
16
+ }
17
+
18
+ export async function connectDatabase() {
19
+ await prisma.$connect();
20
+ await prisma.$queryRaw`SELECT 1`;
21
+ logger.info('Connected to PostgreSQL');
22
+ }
23
+
24
+ export async function disconnectDatabase() {
25
+ await prisma.$disconnect();
26
+ }
27
+
28
+ // A live check: the pool reconnects on its own, so a flag set at startup would lie.
29
+ export async function isDatabaseConnected() {
30
+ let timer: NodeJS.Timeout | undefined;
31
+ const timeout = new Promise((_resolve, reject) => {
32
+ timer = setTimeout(
33
+ () => reject(new Error('Database health check timed out')),
34
+ HEALTH_TIMEOUT_MS,
35
+ );
36
+ });
37
+ try {
38
+ await Promise.race([prisma.$queryRaw`SELECT 1`, timeout]);
39
+ return true;
40
+ } catch {
41
+ return false;
42
+ } finally {
43
+ clearTimeout(timer);
44
+ }
45
+ }
46
+
47
+ const INVALID_TEXT_REPRESENTATION = '22P02'; // Postgres: malformed uuid
48
+
49
+ // Turns Prisma errors into ApiErrors. Returns null for anything it does not know.
50
+ export function mapDatabaseError(err: PrismaError | null | undefined) {
51
+ const cause = err?.meta?.driverAdapterError?.cause;
52
+ switch (err?.code) {
53
+ case 'P2002': {
54
+ // The driver adapter reports the violated constraint, e.g. { index: 'users_email_key' }.
55
+ const target = err.meta?.target ?? Object.values(cause?.constraint ?? {});
56
+ const fields = [target].flat().map(String);
57
+ return fields.some((name) => name.includes('email'))
58
+ ? ApiError.conflict('Email is already registered')
59
+ : ApiError.conflict('Resource already exists');
60
+ }
61
+ case 'P2025':
62
+ return ApiError.notFound();
63
+ case 'P2023':
64
+ return ApiError.badRequest('Invalid id');
65
+ case 'P2007':
66
+ return cause?.originalCode === INVALID_TEXT_REPRESENTATION
67
+ ? ApiError.badRequest('Invalid id')
68
+ : null;
69
+ default:
70
+ return null;
71
+ }
72
+ }
@@ -0,0 +1,3 @@
1
+ import { z } from 'zod';
2
+
3
+ export const databaseEnvSchema = z.object({ DATABASE_URL: z.string().url() });
@@ -0,0 +1,3 @@
1
+ import { z } from 'zod';
2
+
3
+ export const idSchema = z.uuid({ message: 'Invalid id' });
@@ -0,0 +1,9 @@
1
+ import { PrismaPg } from '@prisma/adapter-pg';
2
+ import { env } from '../config/env.ts';
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,111 @@
1
+ import { prisma } from '../../database/prisma.ts';
2
+ import type { Role } from '../../constants/roles.ts';
3
+ import type { PublicUser } from '../../docs/openapi.registry.ts';
4
+ import type { Prisma } from '../../generated/prisma/client.ts';
5
+ import type { UserRepository, UserWithPassword } from './user.service.ts';
6
+
7
+ type CreateUserInput = Parameters<UserRepository['create']>[0];
8
+ type PrismaCodeError = { code?: unknown } | null | undefined;
9
+
10
+ // Every query returns only these fields, so the password hash cannot leak by accident.
11
+ const publicUserSelect = {
12
+ id: true,
13
+ name: true,
14
+ email: true,
15
+ role: true,
16
+ createdAt: true,
17
+ updatedAt: true,
18
+ } satisfies Prisma.UserSelect;
19
+
20
+ export async function findById(id: string) {
21
+ return prisma.user.findUnique({ where: { id }, select: publicUserSelect });
22
+ }
23
+
24
+ export function findByEmail(
25
+ email: string,
26
+ options?: { withPassword?: false },
27
+ ): Promise<PublicUser | null>;
28
+ export function findByEmail(
29
+ email: string,
30
+ options: { withPassword: true },
31
+ ): Promise<UserWithPassword | null>;
32
+ export async function findByEmail(email: string, { withPassword = false } = {}) {
33
+ return prisma.user.findUnique({
34
+ where: { email: email.trim().toLowerCase() },
35
+ select: withPassword ? { ...publicUserSelect, password: true } : publicUserSelect,
36
+ });
37
+ }
38
+
39
+ export async function create({ name, email, password, role }: CreateUserInput) {
40
+ return prisma.user.create({
41
+ data: { name, email: email.trim().toLowerCase(), password, role },
42
+ select: publicUserSelect,
43
+ });
44
+ }
45
+
46
+ export async function findMany({ page, limit }: { page: number; limit: number }) {
47
+ const [users, total] = await prisma.$transaction([
48
+ prisma.user.findMany({
49
+ select: publicUserSelect,
50
+ orderBy: [{ createdAt: 'desc' }, { id: 'desc' }],
51
+ skip: (page - 1) * limit,
52
+ take: limit,
53
+ }),
54
+ prisma.user.count(),
55
+ ]);
56
+ return { users, total };
57
+ }
58
+
59
+ export async function updateRole(id: string, role: Role) {
60
+ try {
61
+ return await prisma.user.update({ where: { id }, data: { role }, select: publicUserSelect });
62
+ } catch (err) {
63
+ if ((err as PrismaCodeError)?.code === 'P2025') return null;
64
+ throw err;
65
+ }
66
+ }
67
+
68
+ // Refresh tokens are removed by the ON DELETE CASCADE foreign key.
69
+ export async function deleteById(id: string) {
70
+ try {
71
+ await prisma.user.delete({ where: { id } });
72
+ return true;
73
+ } catch (err) {
74
+ if ((err as PrismaCodeError)?.code === 'P2025') return false;
75
+ throw err;
76
+ }
77
+ }
78
+
79
+ export async function saveRefreshToken({
80
+ userId,
81
+ tokenHash,
82
+ expiresAt,
83
+ }: {
84
+ userId: string;
85
+ tokenHash: string;
86
+ expiresAt: Date;
87
+ }) {
88
+ await prisma.refreshToken.create({ data: { userId, tokenHash, expiresAt } });
89
+ }
90
+
91
+ export async function findRefreshToken(tokenHash: string) {
92
+ return prisma.refreshToken.findUnique({
93
+ where: { tokenHash },
94
+ select: { userId: true, expiresAt: true, revokedAt: true },
95
+ });
96
+ }
97
+
98
+ export async function revokeRefreshToken(tokenHash: string) {
99
+ const { count } = await prisma.refreshToken.updateMany({
100
+ where: { tokenHash, revokedAt: null },
101
+ data: { revokedAt: new Date() },
102
+ });
103
+ return count > 0;
104
+ }
105
+
106
+ export async function revokeAllRefreshTokens(userId: string) {
107
+ await prisma.refreshToken.updateMany({
108
+ where: { userId, revokedAt: null },
109
+ data: { revokedAt: new Date() },
110
+ });
111
+ }
@@ -0,0 +1,19 @@
1
+ import { afterEach, describe, expect, it, vi } from 'vitest';
2
+ import { isDatabaseConnected } from '../src/database/connection.ts';
3
+ import { prisma } from '../src/database/prisma.ts';
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(
15
+ new Promise(() => {}) as ReturnType<typeof prisma.$queryRaw>,
16
+ );
17
+ expect(await isDatabaseConnected()).toBe(false);
18
+ });
19
+ });