@saasmakers/adonis-core
v0.3.1
Published
Shared AdonisJS building blocks for SaaS Makers projects
Readme
@saasmakers/adonis-core
Shared AdonisJS building blocks for the SaaS Makers APIs (SaaS Makers, Resilience Club, Companies), outside of authentication (see @saasmakers/adonis-auth).
The package only holds code that is identical across apps. App-specific parts stay in each app: config, routes, the ApiContract and socket types, and start/health.ts (it reads the app's connections).
Installation
pnpm add @saasmakers/adonis-coreIn the SaaS Makers monorepo, use "@saasmakers/adonis-core": "workspace:*". In other monorepos, pin the version in the pnpm catalog and reference it with "catalog:".
@adonisjs/core is a required peer dependency. The others are optional and only needed by the subpaths that use them:
| Subpath | Peer dependencies |
| --- | --- |
| exceptions | @adonisjs/limiter, @sentry/node |
| health | @adonisjs/lucid, @adonisjs/redis |
| middlewares/locale | @adonisjs/i18n |
| models | @adonisjs/lucid |
| sockets | @adonisjs/lucid, @adonisjs/transmit |
Entry points
| Import | Content |
| --- | --- |
| @saasmakers/adonis-core | HttpError and all types |
| @saasmakers/adonis-core/exceptions | HttpExceptionHandler |
| @saasmakers/adonis-core/health | defineHealthChecks, defineHealthController |
| @saasmakers/adonis-core/middlewares/{locale,request_logger} | Global middlewares, lazy-loaded by the router |
| @saasmakers/adonis-core/models | TheBaseModel, CamelCaseNamingStrategy, prepareJsonbArray |
| @saasmakers/adonis-core/sockets | defineSocketModel |
Exceptions, health, middlewares, models and sockets live on subpaths because they load Adonis services, which must not run when an app only imports HttpError.
HttpError
Re-export the class narrowed to the app's error codes, so new HttpError() stays type-checked and instanceof keeps working in the exception handler:
// app/errors/HttpError.ts
import { HttpError as BaseHttpError } from '@saasmakers/adonis-core'
const HttpError = BaseHttpError<HttpErrorCode>
export default HttpErrorHttpErrorStatus (400 | 401 | 403 | 404 | 409 | 429) is defined by the package and used by default. @saasmakers/adonis-auth throws this same class and re-exports it, so an app must resolve a single copy of @saasmakers/adonis-core.
Exception handler and middlewares
// start/kernel.ts
server.errorHandler(() => import('@saasmakers/adonis-core/exceptions'))
router.use([
() => import('@adonisjs/core/bodyparser_middleware'),
() => import('@saasmakers/adonis-core/middlewares/locale'),
() => import('@saasmakers/adonis-core/middlewares/request_logger'),
])| Export | Behaviour |
| --- | --- |
| HttpExceptionHandler | Sends HttpError as { code, message, status } with a camelCase message, limiter errors as TooManyRequests (429), and reports errors from 500 to Sentry with the request and ctx.currentUser |
| LocaleMiddleware | Negotiates Accept-Language with @adonisjs/i18n, falls back to the default locale, then sets ctx.i18n, request.locale and request.localeCapitalized, and shares i18n with Edge views when present |
| RequestLoggerMiddleware | Logs the method, URL, status, duration and sorted params of each request at the debug level |
The app declares request.locale, request.localeCapitalized and ctx.currentUser on HttpContext through module augmentation.
Health
// start/health.ts
export const healthChecks = defineHealthChecks({
db: db.connection('postgres'),
redis: redis.connection(),
})
// app/controllers/HealthController.ts
export default defineHealthController<ApiContract['health']>(healthChecks)defineHealthChecks registers the database, connection count, disk space (warns at 80%, fails at 90%), memory heap (300 MB, 700 MB), Redis and Redis memory (100 MB, 120 MB) checks, each cached for 30 seconds.
The controller exposes fetchHealth ({ status: 'alive' }) and fetchHealthChecks (the report, with a 503 status when unhealthy). The optional generic takes the app's ApiContract['health']: the call stops type-checking when these responses no longer satisfy it.
Models
import { TheBaseModel } from '@saasmakers/adonis-core/models'
export default class Tag extends TheBaseModel {}TheBaseModel uses CamelCaseNamingStrategy: snake_case columns in the database, camelCase serialized properties and pagination meta keys. prepareJsonbArray(value) stringifies an array before saving it to a jsonb column, and keeps null and undefined as is.
Sockets
defineSocketModel builds the base model of the realtime models, typed with the app's channels and events:
// app/models/abstract/SocketModel.ts
export default class SocketModel extends defineSocketModel<SocketChannel, SocketEvent>() {}
// app/models/Task.ts
export default class Task extends SocketModel {
public static readonly channel = 'users/:userId/tasks'
}
Task.broadcast({
event,
userId,
})broadcast replaces :userId in the model's channel and always goes through transmit.broadcast, so the event is published on the Redis bus and reaches the clients connected to other API instances. It throws when the channel is missing or has no :userId placeholder.
Testing
Package tests run with pnpm test (Vitest). Behaviour that depends on an app (routes, database, Redis, translations) is tested in each app.
Releasing
Versions are managed with changesets: add a changeset, run changeset version, then publish this package only with pnpm publish from its folder.
