Compare commits

...

3 Commits

Author SHA1 Message Date
0f8b6c6b29
chore: fix tailwindcss content pattern matching node_modules
Some checks failed
Chromatic / chromatic (push) Successful in 6m2s
CI / ci (push) Failing after 54s
CI / commitlint (push) Successful in 15s
Ref: https://x.com/adamwathan/status/1821286325259239554
2024-08-09 23:04:38 +01:00
94af8462d3
chore: stricter tsconfig.json 2024-08-09 22:52:02 +01:00
d020552af5
feat: init apps/api 2024-08-09 22:51:41 +01:00
43 changed files with 4240 additions and 779 deletions

View File

@ -1 +1,8 @@
WEBSITE_PORT=5000 WEBSITE_PORT=5000
API_PORT=5500
DATABASE_USER=wikipedia_user
DATABASE_PASSWORD=password
DATABASE_NAME=wikipedia
DATABASE_HOST=127.0.0.1
DATABASE_PORT=3306

2
.gitignore vendored
View File

@ -20,7 +20,7 @@ build/
.DS_Store .DS_Store
*.pem *.pem
.turbo .turbo
bin/ tmp/
cache.json cache.json
data/dump data/dump
data/sql/* data/sql/*

View File

@ -22,6 +22,7 @@ Available online: <https://wikipedia-game-solver.theoludwig.fr>
- [Node.js](https://nodejs.org/) >= 22.0.0 - [Node.js](https://nodejs.org/) >= 22.0.0
- [pnpm](https://pnpm.io/) >= 9.5.0 - [pnpm](https://pnpm.io/) >= 9.5.0
- [Docker](https://www.docker.com/)
### Installation ### Installation
@ -32,6 +33,7 @@ cd wikipedia-game-solver
# Configure environment variables # Configure environment variables
cp .env.example .env cp .env.example .env
cp apps/website/.env.example apps/website/.env cp apps/website/.env.example apps/website/.env
cp apps/api/.env.example apps/api/.env
# Install dependencies # Install dependencies
pnpm install --frozen-lockfile pnpm install --frozen-lockfile
@ -43,9 +45,12 @@ pnpm exec playwright install --with-deps
### Development ### Development
```sh ```sh
# Start the development server # Start the development servers
node --run dev node --run dev
# Start the development Docker services (e.g: Database)
docker compose up --file compose.dev.yaml
# Lint # Lint
node --run lint:editorconfig node --run lint:editorconfig
node --run lint:prettier node --run lint:prettier
@ -57,6 +62,10 @@ node --run test
# Build # Build
node --run build node --run build
# To execute a command in a specific package (e.g: apps/api)
cd apps/api
node --run ace -- list
``` ```
### Production environment with [Docker](https://www.docker.com/) ### Production environment with [Docker](https://www.docker.com/)
@ -68,7 +77,8 @@ docker compose up --build
#### Services started #### Services started
`wikipedia-game-solver`: <http://127.0.0.1:5000> - `apps/website`: <http://127.0.0.1:5000>
- `apps/api`: <http://127.0.0.1:5500>
## License ## License

12
apps/api/.env.example Normal file
View File

@ -0,0 +1,12 @@
TZ=UTC
PORT=5500
HOST=0.0.0.0
LOG_LEVEL=info
APP_KEY=LFGmw8iGkYF7vfS18ZB9-1Gn-6LfmoAk
NODE_ENV=development
DATABASE_USER=wikipedia_user
DATABASE_PASSWORD=password
DATABASE_NAME=wikipedia
DATABASE_HOST=127.0.0.1
DATABASE_PORT=3306

14
apps/api/.eslintrc.json Normal file
View File

@ -0,0 +1,14 @@
{
"root": true,
"extends": ["@repo/eslint-config"],
"overrides": [
{
"files": ["*.ts", "*.tsx"],
"plugins": ["@typescript-eslint"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"project": true
}
}
]
}

29
apps/api/Dockerfile Normal file
View File

@ -0,0 +1,29 @@
FROM node:22.4.1-slim AS node-pnpm
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable
WORKDIR /usr/src/app
FROM node-pnpm AS builder
RUN pnpm install --global turbo@2.0.12
COPY ./ ./
RUN turbo prune @repo/api --docker
FROM node-pnpm AS installer
COPY .gitignore .gitignore
COPY --from=builder /usr/src/app/out/json/ ./
COPY --from=builder /usr/src/app/out/pnpm-lock.yaml ./pnpm-lock.yaml
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --frozen-lockfile --prod
COPY --from=builder /usr/src/app/out/full/ ./
COPY turbo.json turbo.json
# RUN pnpm --filter=@repo/api... exec turbo run build
FROM node-pnpm AS runner
ENV NODE_ENV=production
ENV HOSTNAME=0.0.0.0
RUN addgroup --system --gid 1001 nodejs && adduser --system --uid 1001 applicationrunner
USER applicationrunner
COPY --from=installer --chown=applicationrunner:nodejs /usr/src/app ./
WORKDIR /usr/src/app/apps/api
CMD ["node", "--import=tsx", "./src/bin/server.ts"]

46
apps/api/package.json Normal file
View File

@ -0,0 +1,46 @@
{
"name": "@repo/api",
"version": "1.0.0-staging.3",
"private": true,
"type": "module",
"imports": {
"#*": "./src/*"
},
"scripts": {
"start": "node --import=tsx ./src/bin/server.ts",
"dev": "node --import=tsx --watch --watch-preserve-output ./src/bin/server.ts",
"ace": "node --import=tsx ./src/bin/console.ts",
"test": "node --import=tsx ./src/bin/test.ts",
"lint:eslint": "eslint src --max-warnings 0 --report-unused-disable-directives",
"lint:typescript": "tsc --noEmit"
},
"dependencies": {
"@adonisjs/auth": "catalog:",
"@adonisjs/core": "catalog:",
"@adonisjs/cors": "catalog:",
"@adonisjs/lucid": "catalog:",
"@repo/utils": "workspace:*",
"@repo/wikipedia-game-solver": "workspace:*",
"@vinejs/vine": "catalog:",
"luxon": "catalog:",
"mysql2": "catalog:",
"reflect-metadata": "catalog:",
"tsx": "catalog:",
"pino-pretty": "catalog:"
},
"devDependencies": {
"@adonisjs/assembler": "catalog:",
"@japa/api-client": "catalog:",
"@japa/assert": "catalog:",
"@japa/plugin-adonisjs": "catalog:",
"@japa/runner": "catalog:",
"@repo/config-typescript": "workspace:*",
"@repo/eslint-config": "workspace:*",
"@total-typescript/ts-reset": "catalog:",
"@types/luxon": "catalog:",
"@types/node": "catalog:",
"eslint": "catalog:",
"openapi-types": "catalog:",
"typescript": "catalog:"
}
}

56
apps/api/src/adonisrc.ts Normal file
View File

@ -0,0 +1,56 @@
import { defineConfig } from "@adonisjs/core/app"
export default defineConfig({
commands: [
async () => {
return await import("@adonisjs/core/commands")
},
async () => {
return await import("@adonisjs/lucid/commands")
},
],
providers: [
async () => {
return await import("@adonisjs/core/providers/app_provider")
},
async () => {
return await import("@adonisjs/core/providers/hash_provider")
},
{
file: async () => {
return await import("@adonisjs/core/providers/repl_provider")
},
environment: ["repl", "test"],
},
async () => {
return await import("@adonisjs/core/providers/vinejs_provider")
},
async () => {
return await import("@adonisjs/cors/cors_provider")
},
async () => {
return await import("@adonisjs/lucid/database_provider")
},
async () => {
return await import("@adonisjs/auth/auth_provider")
},
],
preloads: [
async () => {
return await import("#start/routes.js")
},
async () => {
return await import("#start/kernel.js")
},
],
tests: {
suites: [
{
files: ["**/*.test.ts"],
name: "functional",
timeout: 30_000,
},
],
forceExit: false,
},
})

View File

@ -0,0 +1,32 @@
import type { HttpContext } from "@adonisjs/core/http"
import { ExceptionHandler } from "@adonisjs/core/http"
import app from "@adonisjs/core/services/app"
export default class HttpExceptionHandler extends ExceptionHandler {
/**
* In debug mode, the exception handler will display verbose errors with pretty printed stack traces.
*/
protected override debug = !app.inProduction
/**
* The method is used for handling errors and returning response to the client.
*/
public override async handle(
error: unknown,
ctx: HttpContext,
): Promise<unknown> {
return await super.handle(error, ctx)
}
/**
* The method is used to report error to the logging service or the third party error monitoring service.
*
* @note You should not attempt to send a response from this method.
*/
public override async report(
error: unknown,
ctx: HttpContext,
): Promise<void> {
return await super.report(error, ctx)
}
}

View File

@ -0,0 +1,27 @@
import type { Authenticators } from "@adonisjs/auth/types"
import type { HttpContext } from "@adonisjs/core/http"
import type { NextFn } from "@adonisjs/core/types/http"
/**
* Auth middleware is used authenticate HTTP requests and deny
* access to unauthenticated users.
*/
export default class AuthMiddleware {
/**
* The URL to redirect to, when authentication fails
*/
redirectTo = "/login"
public async handle(
ctx: HttpContext,
next: NextFn,
options: {
guards?: Array<keyof Authenticators>
} = {},
): Promise<void> {
await ctx.auth.authenticateUsing(options.guards, {
loginRoute: this.redirectTo,
})
return next()
}
}

View File

@ -0,0 +1,18 @@
import { HttpContext } from "@adonisjs/core/http"
import { Logger } from "@adonisjs/core/logger"
import type { NextFn } from "@adonisjs/core/types/http"
/**
* The container bindings middleware binds classes to their request specific value using the container resolver.
*
* - We bind "HttpContext" class to the "ctx" object.
* - And bind "Logger" class to the "ctx.logger" object.
*/
export default class ContainerBindingsMiddleware {
public async handle(ctx: HttpContext, next: NextFn): Promise<void> {
ctx.containerResolver.bindValue(HttpContext, ctx)
ctx.containerResolver.bindValue(Logger, ctx.logger)
return next()
}
}

View File

@ -0,0 +1,14 @@
import type { HttpContext } from "@adonisjs/core/http"
import type { NextFn } from "@adonisjs/core/types/http"
/**
* Updating the "Accept" header to always accept "application/json" response from the server. This will force the internals of the framework like validator errors or auth errors to return a JSON response.
*/
export default class ForceJsonResponseMiddleware {
public async handle({ request }: HttpContext, next: NextFn): Promise<void> {
const headers = request.headers()
headers.accept = "application/json"
return next()
}
}

View File

@ -0,0 +1,51 @@
import { DbAccessTokensProvider } from "@adonisjs/auth/access_tokens"
import { withAuthFinder } from "@adonisjs/auth/mixins/lucid"
import { compose } from "@adonisjs/core/helpers"
import hash from "@adonisjs/core/services/hash"
import { BaseModel, column } from "@adonisjs/lucid/orm"
import { DateTime } from "luxon"
const AuthFinder = withAuthFinder(
() => {
return hash.use("scrypt")
},
{
uids: ["email"],
passwordColumnName: "password",
},
)
export default class User extends compose(BaseModel, AuthFinder) {
protected tableName = "users"
@column({ columnName: "id", isPrimary: true })
declare id: number
@column({
columnName: "full_name",
})
declare fullName: string | null
@column({
columnName: "email",
})
declare email: string
@column({ columnName: "password", serializeAs: null })
declare password: string
@column.dateTime({
columnName: "created_at",
autoCreate: true,
})
declare createdAt: DateTime
@column.dateTime({
columnName: "updated_at",
autoCreate: true,
autoUpdate: true,
})
declare updatedAt: DateTime | null
static accessTokens = DbAccessTokensProvider.forModel(User)
}

View File

@ -0,0 +1,7 @@
import router from "@adonisjs/core/services/router"
router.get("/", async () => {
return {
hello: "world",
}
})

View File

@ -0,0 +1 @@
import "./get.js"

View File

@ -0,0 +1,16 @@
import { test } from "@japa/runner"
test.group("GET /", () => {
test("should get hello world", async ({ client }) => {
// Arrange - Given
// Act - When
const response = await client.get("/")
// Assert - Then
response.assertStatus(200)
response.assertBody({
hello: "world",
})
})
})

48
apps/api/src/bin/console.ts Executable file
View File

@ -0,0 +1,48 @@
#!/usr/bin/env -S node --import=tsx
/**
* Ace entry point
*
* Entrypoint for booting the AdonisJS command-line framework and executing commands.
* Commands do not boot the application, unless the currently running command has `options.startApp` flag set to true.
*/
import { Ignitor, prettyPrintError } from "@adonisjs/core"
import "reflect-metadata"
/**
* URL to the application root. AdonisJS need it to resolve paths to file and directories for scaffolding commands
*/
const APP_ROOT = new URL("../", import.meta.url)
/**
* The importer is used to import files in context of the application.
*/
const IMPORTER = async (filePath: string): Promise<unknown> => {
if (filePath.startsWith("./") || filePath.startsWith("../")) {
return await import(new URL(filePath, APP_ROOT).href)
}
return await import(filePath)
}
const ignitor = new Ignitor(APP_ROOT, { importer: IMPORTER })
try {
await ignitor
.tap((app) => {
app.booting(async () => {
await import("#start/env.js")
})
app.listen("SIGTERM", async () => {
return await app.terminate()
})
app.listenIf(app.managedByPm2, "SIGINT", async () => {
return await app.terminate()
})
})
.ace()
.handle(process.argv.splice(2))
} catch (error) {
process.exitCode = 1
await prettyPrintError(error)
}

47
apps/api/src/bin/server.ts Executable file
View File

@ -0,0 +1,47 @@
#!/usr/bin/env -S node --import=tsx
/**
* HTTP server entrypoint
*
* Entrypoint for starting the AdonisJS HTTP server.
*/
import { Ignitor, prettyPrintError } from "@adonisjs/core"
import "reflect-metadata"
/**
* URL to the application root. AdonisJS need it to resolve paths to file and directories for scaffolding commands.
*/
const APP_ROOT = new URL("../", import.meta.url)
/**
* The importer is used to import files in context of the application.
*/
const IMPORTER = async (filePath: string): Promise<unknown> => {
if (filePath.startsWith("./") || filePath.startsWith("../")) {
return await import(new URL(filePath, APP_ROOT).href)
}
return await import(filePath)
}
const ignitor = new Ignitor(APP_ROOT, { importer: IMPORTER })
try {
await ignitor
.tap((app) => {
app.booting(async () => {
await import("#start/env.js")
})
app.listen("SIGTERM", async () => {
return await app.terminate()
})
app.listenIf(app.managedByPm2, "SIGINT", async () => {
return await app.terminate()
})
})
.httpServer()
.start()
} catch (error) {
process.exitCode = 1
await prettyPrintError(error)
}

69
apps/api/src/bin/test.ts Executable file
View File

@ -0,0 +1,69 @@
#!/usr/bin/env -S node --import=tsx
/**
* Test runner entrypoint
*
* Entrypoint for running tests using Japa.
*/
process.env["NODE_ENV"] = "test"
import { Ignitor, prettyPrintError } from "@adonisjs/core"
import { configure, processCLIArgs, run } from "@japa/runner"
import "reflect-metadata"
/**
* URL to the application root. AdonisJS need it to resolve paths to file and directories for scaffolding commands
*/
const APP_ROOT = new URL("../", import.meta.url)
/**
* The importer is used to import files in context of the application.
*/
const IMPORTER = async (filePath: string): Promise<unknown> => {
if (filePath.startsWith("./") || filePath.startsWith("../")) {
return await import(new URL(filePath, APP_ROOT).href)
}
return await import(filePath)
}
const ignitor = new Ignitor(APP_ROOT, { importer: IMPORTER })
try {
await ignitor
.tap((app) => {
app.booting(async () => {
await import("#start/env.js")
})
app.listen("SIGTERM", async () => {
return await app.terminate()
})
app.listenIf(app.managedByPm2, "SIGINT", async () => {
return await app.terminate()
})
})
.testRunner()
.configure(async (app) => {
const { runnerHooks, ...config } = await import("#tests/bootstrap.js")
processCLIArgs(process.argv.splice(2))
configure({
...app.rcFile.tests,
...config,
...{
setup: runnerHooks.setup,
teardown: runnerHooks.teardown.concat([
async () => {
return await app.terminate()
},
]),
},
})
})
.run(async () => {
return await run()
})
} catch (error) {
process.exitCode = 1
await prettyPrintError(error)
}

View File

@ -0,0 +1,37 @@
import env from "#start/env.js"
import { Secret } from "@adonisjs/core/helpers"
import { defineConfig } from "@adonisjs/core/http"
import app from "@adonisjs/core/services/app"
/**
* The app key is used for encrypting cookies, generating signed URLs, and by the "encryption" module.
*
* The encryption module will fail to decrypt data if the key is lost or changed.
* Therefore it is recommended to keep the app key secure.
*/
export const appKey = new Secret(env.get("APP_KEY"))
/**
* The configuration settings used by the HTTP server
*/
export const http = defineConfig({
generateRequestId: true,
allowMethodSpoofing: false,
/**
* Enabling async local storage will let you access HTTP context from anywhere inside your application.
*/
useAsyncLocalStorage: false,
/**
* Manage cookies configuration. The settings for the session id cookie are defined inside the "config/session.ts" file.
*/
cookie: {
domain: "",
path: "/",
maxAge: "2h",
httpOnly: true,
secure: app.inProduction,
sameSite: "lax",
},
})

View File

@ -0,0 +1,29 @@
import { defineConfig } from "@adonisjs/auth"
import { tokensGuard, tokensUserProvider } from "@adonisjs/auth/access_tokens"
import type { Authenticators, InferAuthEvents } from "@adonisjs/auth/types"
const authConfig = defineConfig({
default: "api",
guards: {
api: tokensGuard({
provider: tokensUserProvider({
tokens: "accessTokens",
model: async () => {
return await import("#app/models/user.js")
},
}),
}),
},
})
export default authConfig
/**
* Inferring types from the configured auth guards.
*/
declare module "@adonisjs/auth/types" {
interface Authenticators extends InferAuthenticators<typeof authConfig> {}
}
declare module "@adonisjs/core/types" {
interface EventsList extends InferAuthEvents<Authenticators> {}
}

View File

@ -0,0 +1,50 @@
import { defineConfig } from "@adonisjs/core/bodyparser"
const bodyParserConfig = defineConfig({
/**
* The bodyparser middleware will parse the request body for the following HTTP methods.
*/
allowedMethods: ["POST", "PUT", "PATCH", "DELETE"],
/**
* Config for the "application/x-www-form-urlencoded" content-type parser.
*/
form: {
convertEmptyStringsToNull: true,
types: ["application/x-www-form-urlencoded"],
},
/**
* Config for the JSON parser
*/
json: {
convertEmptyStringsToNull: true,
types: [
"application/json",
"application/json-patch+json",
"application/vnd.api+json",
"application/csp-report",
],
},
/**
* Config for the "multipart/form-data" content-type parser.
* File uploads are handled by the multipart parser.
*/
multipart: {
/**
* Enabling auto process allows bodyparser middleware to move all uploaded files inside the tmp folder of your operating system.
*/
autoProcess: true,
convertEmptyStringsToNull: true,
processManually: [],
/**
* Maximum limit of data to parse including all files and fields.
*/
limit: "20mb",
types: ["multipart/form-data"],
},
})
export default bodyParserConfig

View File

@ -0,0 +1,18 @@
import { defineConfig } from "@adonisjs/cors"
/**
* Configuration options to tweak the CORS policy. The following options are documented on the official documentation website.
*
* https://docs.adonisjs.com/guides/security/cors
*/
const corsConfig = defineConfig({
enabled: true,
origin: true,
methods: ["GET", "HEAD", "POST", "PUT", "DELETE"],
headers: true,
exposeHeaders: [],
credentials: true,
maxAge: 90,
})
export default corsConfig

View File

@ -0,0 +1,24 @@
import env from "#start/env.js"
import { defineConfig } from "@adonisjs/lucid"
const databaseConfig = defineConfig({
connection: "mysql",
connections: {
mysql: {
client: "mysql2",
connection: {
host: env.get("DATABASE_HOST"),
port: env.get("DATABASE_PORT"),
user: env.get("DATABASE_USER"),
password: env.get("DATABASE_PASSWORD"),
database: env.get("DATABASE_NAME"),
},
migrations: {
naturalSort: true,
paths: ["database/migrations"],
},
},
},
})
export default databaseConfig

View File

@ -0,0 +1,24 @@
import { defineConfig, drivers } from '@adonisjs/core/hash'
const hashConfig = defineConfig({
default: 'scrypt',
list: {
scrypt: drivers.scrypt({
cost: 16384,
blockSize: 8,
parallelization: 1,
maxMemory: 33554432,
}),
},
})
export default hashConfig
/**
* Inferring types for the list of hashers you have configured
* in your application.
*/
declare module '@adonisjs/core/types' {
export interface HashersList extends InferHashers<typeof hashConfig> {}
}

View File

@ -0,0 +1,34 @@
import env from "#start/env.js"
import { defineConfig, targets } from "@adonisjs/core/logger"
import app from "@adonisjs/core/services/app"
const loggerConfig = defineConfig({
default: "app",
/**
* The loggers object can be used to define multiple loggers.
* By default, we configure only one logger (named "app").
*/
loggers: {
app: {
enabled: true,
name: env.get("APP_NAME"),
level: env.get("LOG_LEVEL"),
transport: {
targets: targets()
.pushIf(!app.inProduction, targets.pretty())
.pushIf(app.inProduction, targets.file({ destination: 1 }))
.toArray(),
},
},
},
})
export default loggerConfig
/**
* Inferring types for the list of loggers you have configured in your application.
*/
declare module "@adonisjs/core/types" {
export interface LoggersList extends InferLoggers<typeof loggerConfig> {}
}

View File

@ -0,0 +1,21 @@
import { BaseSchema } from "@adonisjs/lucid/schema"
export default class CreateUsersTable extends BaseSchema {
protected tableName = "users"
public override async up(): Promise<void> {
await this.schema.createTable(this.tableName, (table) => {
table.increments("id").notNullable()
table.string("full_name").nullable()
table.string("email", 254).notNullable().unique()
table.string("password").notNullable()
table.timestamp("created_at").notNullable()
table.timestamp("updated_at").nullable()
})
}
public override async down(): Promise<void> {
await this.schema.dropTable(this.tableName)
}
}

View File

@ -0,0 +1,31 @@
import { BaseSchema } from "@adonisjs/lucid/schema"
export default class CreateAccessTokensTable extends BaseSchema {
protected tableName = "auth_access_tokens"
public override async up(): Promise<void> {
await this.schema.createTable(this.tableName, (table) => {
table.increments("id")
table
.integer("tokenable_id")
.notNullable()
.unsigned()
.references("id")
.inTable("users")
.onDelete("CASCADE")
table.string("type").notNullable()
table.string("name").nullable()
table.string("hash").notNullable()
table.text("abilities").notNullable()
table.timestamp("created_at")
table.timestamp("updated_at")
table.timestamp("last_used_at").nullable()
table.timestamp("expires_at").nullable()
})
}
public override async down(): Promise<void> {
await this.schema.dropTable(this.tableName)
}
}

29
apps/api/src/start/env.ts Normal file
View File

@ -0,0 +1,29 @@
/**
* Environment variables service
*/
import { Env } from "@adonisjs/core/env"
export default await Env.create(new URL("../..", import.meta.url), {
NODE_ENV: Env.schema.enum(["development", "production", "test"] as const),
PORT: Env.schema.number(),
APP_KEY: Env.schema.string(),
HOST: Env.schema.string({ format: "host" }),
LOG_LEVEL: Env.schema.enum([
"fatal",
"error",
"warn",
"info",
"debug",
"trace",
] as const),
/**
* Variables for configuring database connection
*/
DATABASE_HOST: Env.schema.string({ format: "host" }),
DATABASE_PORT: Env.schema.number(),
DATABASE_USER: Env.schema.string(),
DATABASE_PASSWORD: Env.schema.string(),
DATABASE_NAME: Env.schema.string(),
})

View File

@ -0,0 +1,54 @@
/**
* HTTP kernel file
*
* The HTTP kernel file is used to register the middleware with the server or the router.
*/
import router from "@adonisjs/core/services/router"
import server from "@adonisjs/core/services/server"
/**
* The error handler is used to convert an exception
* to a HTTP response.
*/
server.errorHandler(async () => {
return await import("#app/exceptions/handler.js")
})
/**
* The server middleware stack runs middleware on all the HTTP
* requests, even if there is no route registered for
* the request URL.
*/
server.use([
async () => {
return await import("#app/middleware/container_bindings_middleware.js")
},
async () => {
return await import("#app/middleware/force_json_response_middleware.js")
},
async () => {
return await import("@adonisjs/cors/cors_middleware")
},
])
/**
* The router middleware stack runs middleware on all the HTTP requests with a registered route.
*/
router.use([
async () => {
return await import("@adonisjs/core/bodyparser_middleware")
},
async () => {
return await import("@adonisjs/auth/initialize_auth_middleware")
},
])
/**
* Named middleware collection must be explicitly assigned to the routes or the routes group.
*/
export const middleware = router.named({
auth: async () => {
return await import("#app/middleware/auth_middleware.js")
},
})

View File

@ -0,0 +1,7 @@
/**
* Routes file
*
* The routes file is used for defining the HTTP routes.
*/
import "#app/routes/index.js"

View File

@ -0,0 +1,41 @@
import app from "@adonisjs/core/services/app"
import testUtils from "@adonisjs/core/services/test_utils"
import { apiClient } from "@japa/api-client"
import { assert } from "@japa/assert"
import { pluginAdonisJS } from "@japa/plugin-adonisjs"
import type { Config } from "@japa/runner/types"
/**
* This file is imported by the "bin/test.ts" entrypoint file
*/
/**
* Configure Japa plugins in the plugins array.
* Learn more - https://japa.dev/docs/runner-config#plugins-optional
*/
export const plugins: Config["plugins"] = [
assert(),
apiClient(),
pluginAdonisJS(app),
]
/**
* Configure lifecycle function to run before and after all the tests.
*
* The setup functions are executed before all the tests.
* The teardown functions are executer after all the tests.
*/
export const runnerHooks: Required<Pick<Config, "setup" | "teardown">> = {
setup: [],
teardown: [],
}
/**
* Configure suites by tapping into the test suite instance.
* Learn more - https://japa.dev/docs/test-suites#lifecycle-hooks
*/
export const configureSuite: Config["configureSuite"] = (suite) => {
return suite.setup(async () => {
return await testUtils.httpServer().start()
})
}

15
apps/api/tsconfig.json Normal file
View File

@ -0,0 +1,15 @@
{
"extends": "@repo/config-typescript/tsconfig.json",
"compilerOptions": {
"target": "ESNext",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"resolveJsonModule": true,
"lib": ["ESNext"],
"types": ["@total-typescript/ts-reset", "@types/node"],
"experimentalDecorators": true,
"emitDecoratorMetadata": true,
"noEmit": true
}
}

View File

@ -11,7 +11,6 @@
}, },
"scripts": { "scripts": {
"start": "node --import=tsx ./src/index.ts", "start": "node --import=tsx ./src/index.ts",
"dev-test": "node --import=tsx --watch --watch-preserve-output ./src/index.ts",
"lint:eslint": "eslint src --max-warnings 0 --report-unused-disable-directives", "lint:eslint": "eslint src --max-warnings 0 --report-unused-disable-directives",
"lint:typescript": "tsc --noEmit" "lint:typescript": "tsc --noEmit"
}, },

View File

@ -2,7 +2,7 @@ import sharedConfig from "@repo/config-tailwind"
/** @type {Pick<import('tailwindcss').Config, "presets" | "content">} */ /** @type {Pick<import('tailwindcss').Config, "presets" | "content">} */
const config = { const config = {
content: [".storybook/preview.tsx", "../../packages/**/*.tsx"], content: [".storybook/preview.tsx", "../../packages/*/src/**/*.tsx"],
presets: [sharedConfig], presets: [sharedConfig],
} }

View File

@ -5,7 +5,7 @@ RUN corepack enable
WORKDIR /usr/src/app WORKDIR /usr/src/app
FROM node-pnpm AS builder FROM node-pnpm AS builder
RUN pnpm install --global turbo@2.0.11 RUN pnpm install --global turbo@2.0.12
COPY ./ ./ COPY ./ ./
RUN turbo prune @repo/website --docker RUN turbo prune @repo/website --docker

View File

@ -2,7 +2,7 @@ import sharedConfig from "@repo/config-tailwind"
/** @type {Pick<import('tailwindcss').Config, "presets" | "content">} */ /** @type {Pick<import('tailwindcss').Config, "presets" | "content">} */
const config = { const config = {
content: ["./**/*.tsx", "../../packages/**/*.tsx"], content: ["./app/**/*.tsx", "../../packages/*/src/**/*.tsx"],
presets: [sharedConfig], presets: [sharedConfig],
} }

41
compose.dev.yaml Normal file
View File

@ -0,0 +1,41 @@
services:
wikipedia-solver-dev-database:
container_name: "wikipedia-solver-dev-database"
image: "mariadb:10.6.17"
restart: "unless-stopped"
env_file: ".env"
environment:
MARIADB_USER: ${DATABASE_USER}
MARIADB_PASSWORD: ${DATABASE_PASSWORD}
MARIADB_ROOT_PASSWORD: ${DATABASE_PASSWORD}
MARIADB_DATABASE: ${DATABASE_NAME}
command:
--innodb_buffer_pool_size=4G
--key-buffer-size=4G
--innodb_log_buffer_size=256M
--innodb_log_file_size=1G
--innodb_write_io_threads=16
--innodb_flush_log_at_trx_commit=0
--max_allowed_packet=1G
ports:
- "${DATABASE_PORT-3306}:${DATABASE_PORT-3306}"
volumes:
- "wikipedia-solver-dev-mariadb-data:/var/lib/mysql"
# - "./sql:/docker-entrypoint-initdb.d/"
wikipedia-solver-dev-adminer:
container_name: "wikipedia-solver-dev-adminer"
image: "adminer:4.8.1"
restart: "unless-stopped"
ports:
- "8080:8080"
env_file: ".env"
environment:
ADMINER_DEFAULT_SERVER: "wikipedia-solver-dev-database"
volumes:
- "./adminer/default-orange.css:/var/www/html/adminer.css"
- "./adminer/logo.png:/var/www/html/logo.png"
- "./adminer/fonts/:/var/www/html/fonts"
volumes:
wikipedia-solver-dev-mariadb-data:

View File

@ -1,7 +1,7 @@
services: services:
wikipedia-game-solver: wikipedia-game-solver-website:
container_name: "wikipedia-game-solver" container_name: "wikipedia-game-solver-website"
image: "wikipedia-game-solver" image: "wikipedia-game-solver-website"
restart: "unless-stopped" restart: "unless-stopped"
build: build:
context: "./" context: "./"
@ -11,3 +11,43 @@ services:
environment: environment:
PORT: ${WEBSITE_PORT-5000} PORT: ${WEBSITE_PORT-5000}
env_file: "./apps/website/.env" env_file: "./apps/website/.env"
wikipedia-game-solver-api:
container_name: "wikipedia-game-solver-api"
image: "wikipedia-game-solver-api"
restart: "unless-stopped"
build:
context: "./"
dockerfile: "./apps/api/Dockerfile"
ports:
- "${API_PORT-5000}:${API_PORT-5000}"
environment:
PORT: ${API_PORT-5000}
env_file: "./apps/api/.env"
wikipedia-solver-database:
container_name: "wikipedia-solver-database"
image: "mariadb:10.6.17"
restart: "unless-stopped"
env_file: ".env"
environment:
MARIADB_USER: ${DATABASE_USER}
MARIADB_PASSWORD: ${DATABASE_PASSWORD}
MARIADB_ROOT_PASSWORD: ${DATABASE_PASSWORD}
MARIADB_DATABASE: ${DATABASE_NAME}
command:
--innodb_buffer_pool_size=4G
--key-buffer-size=4G
--innodb_log_buffer_size=256M
--innodb_log_file_size=1G
--innodb_write_io_threads=16
--innodb_flush_log_at_trx_commit=0
--max_allowed_packet=1G
ports:
- "${DATABASE_PORT-3306}:${DATABASE_PORT-3306}"
volumes:
- "wikipedia-solver-mariadb-data:/var/lib/mysql"
# - "./sql:/docker-entrypoint-initdb.d/"
volumes:
wikipedia-solver-mariadb-data:

View File

@ -29,7 +29,7 @@
"prettier-plugin-tailwindcss": "0.6.5", "prettier-plugin-tailwindcss": "0.6.5",
"replace-in-files-cli": "3.0.0", "replace-in-files-cli": "3.0.0",
"semantic-release": "23.1.1", "semantic-release": "23.1.1",
"turbo": "2.0.11", "turbo": "2.0.12",
"typescript": "catalog:" "typescript": "catalog:"
} }
} }

View File

@ -1,16 +1,21 @@
{ {
"compilerOptions": { "compilerOptions": {
"strict": true, "strict": true,
"strictBindCallApply": true,
"strictFunctionTypes": true,
"allowUnusedLabels": false, "allowUnusedLabels": false,
"allowUnreachableCode": false, "allowUnreachableCode": false,
"noFallthroughCasesInSwitch": true, "noFallthroughCasesInSwitch": true,
"noImplicitOverride": true, "noImplicitOverride": true,
"noImplicitReturns": true, "noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"noPropertyAccessFromIndexSignature": true, "noPropertyAccessFromIndexSignature": true,
"noUncheckedIndexedAccess": true, "noUncheckedIndexedAccess": true,
"noUnusedLocals": true, "noUnusedLocals": true,
"noUnusedParameters": true, "noUnusedParameters": true,
"verbatimModuleSyntax": true,
"isolatedModules": true, "isolatedModules": true,
"esModuleInterop": true, "esModuleInterop": true,
"skipLibCheck": true, "skipLibCheck": true,

3938
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@ -21,15 +21,35 @@ catalog:
# TypeScript # TypeScript
"typescript": "5.5.4" "typescript": "5.5.4"
"@total-typescript/ts-reset": "0.5.1" "@total-typescript/ts-reset": "0.5.1"
"@types/node": "22.0.2" "@types/node": "22.1.0"
"tsx": "4.16.5" "tsx": "4.17.0"
# AdonisJS
"@adonisjs/auth": "9.2.3"
"@adonisjs/core": "6.12.1"
"@adonisjs/cors": "2.2.1"
"@adonisjs/lucid": "21.2.0"
"mysql2": "3.11.0"
"@adonisjs/assembler": "7.7.0"
"@vinejs/vine": "2.1.0"
"luxon": "3.5.0"
"@types/luxon": "3.4.2"
"reflect-metadata": "0.2.2"
"openapi-types": "12.1.3"
"pino-pretty": "11.2.2"
# Japa (AdonisJS Testing)
"@japa/api-client": "2.0.3"
"@japa/assert": "3.0.0"
"@japa/plugin-adonisjs": "3.0.1"
"@japa/runner": "3.1.4"
# ESLint # ESLint
"@typescript-eslint/eslint-plugin": "7.18.0" "@typescript-eslint/eslint-plugin": "7.18.0"
"@typescript-eslint/parser": "7.18.0" "@typescript-eslint/parser": "7.18.0"
"eslint": "8.57.0" "eslint": "8.57.0"
"eslint-config-conventions": "14.4.0" "eslint-config-conventions": "14.4.0"
"eslint-plugin-promise": "7.0.0" "eslint-plugin-promise": "7.1.0"
"eslint-plugin-unicorn": "55.0.0" "eslint-plugin-unicorn": "55.0.0"
"eslint-config-next": "14.2.5" "eslint-config-next": "14.2.5"
"eslint-plugin-storybook": "0.8.0" "eslint-plugin-storybook": "0.8.0"
@ -37,25 +57,25 @@ catalog:
# Storybook # Storybook
"@chromatic-com/storybook": "1.6.1" "@chromatic-com/storybook": "1.6.1"
"@storybook/addon-a11y": "8.2.7" "@storybook/addon-a11y": "8.2.8"
"@storybook/addon-essentials": "8.2.7" "@storybook/addon-essentials": "8.2.8"
"@storybook/addon-interactions": "8.2.7" "@storybook/addon-interactions": "8.2.8"
"@storybook/addon-links": "8.2.7" "@storybook/addon-links": "8.2.8"
"@storybook/addon-storysource": "8.2.7" "@storybook/addon-storysource": "8.2.8"
"@storybook/addon-themes": "8.2.7" "@storybook/addon-themes": "8.2.8"
"@storybook/blocks": "8.2.7" "@storybook/blocks": "8.2.8"
"@storybook/nextjs": "8.2.7" "@storybook/nextjs": "8.2.8"
"@storybook/react": "8.2.7" "@storybook/react": "8.2.8"
"@storybook/test": "8.2.7" "@storybook/test": "8.2.8"
"@storybook/test-runner": "0.19.1" "@storybook/test-runner": "0.19.1"
"chromatic": "11.7.0" "chromatic": "11.7.0"
"http-server": "14.1.1" "http-server": "14.1.1"
"storybook": "8.2.7" "storybook": "8.2.8"
"storybook-dark-mode": "4.0.2" "storybook-dark-mode": "4.0.2"
# Testing # Testing
"playwright": "1.45.3" "playwright": "1.46.0"
"@playwright/test": "1.45.3" "@playwright/test": "1.46.0"
"axe-playwright": "2.0.1" "axe-playwright": "2.0.1"
"start-server-and-test": "2.0.5" "start-server-and-test": "2.0.5"
"@vitest/browser": "2.0.5" "@vitest/browser": "2.0.5"
@ -65,8 +85,8 @@ catalog:
"@testing-library/react": "16.0.0" "@testing-library/react": "16.0.0"
# CSS # CSS
"postcss": "8.4.40" "postcss": "8.4.41"
"tailwindcss": "3.4.7" "tailwindcss": "3.4.9"
"@fontsource/montserrat": "5.0.18" "@fontsource/montserrat": "5.0.18"
"clsx": "2.1.0" "clsx": "2.1.0"
"cva": "1.0.0-beta.1" "cva": "1.0.0-beta.1"