Upgrading to 0.5.5
0.5.1 to 0.5.4 need no code changes: apps written for 0.5.0 keep working. 0.5.1 brings Megh's own ORM setup and DI container, and deprecates app.useDatabase(). 0.5.2 is a bug-fix release. 0.5.3 adds seeders, factories and documented responses, and fixes the ORM on SQL Server. 0.5.4 adds scaffolding to the CLI and documents @Query() parameters.
0.5.5 adds Megh's own validation decorators, exception filters, health checks and request IDs, and fixes a batch of runtime bugs. Most apps need no code changes, but read Breaking in 0.5.5 first: the middleware order changed, and some routes now send the status they declare.
npm i @meghjs/core@^0.5.5
npm i -D @meghjs/cli@^0.5.5Breaking in 0.5.5
@UseMiddlewareruns before authentication. The pipeline is now middleware → authentication →@Authorized→ validation → handler, for global, controller and route middleware alike. Before,@UseMiddlewareran after@Authorizedand could readrequest.user. Move logic that needs the user into the authorization handler or the route, or read the user in a later middleware of your own. See Pipeline order.app.run()listens on0.0.0.0by default instead of localhost, so the app is reachable inside containers. Keep local-only withapp.run(port, { host: '127.0.0.1' })orHOST=127.0.0.1.- Status codes are honoured.
@HttpCode,Results.Created,Results.NoContent,Results.NotFoundandHttpResponse.Creatednow send their status instead of 200. Clients that checked for 200 on these routes need updating. - Unknown routes answer
{ code: 404, status: "Error", message }instead of Fastify's default 404 body. MeghTestuses the production error handler, so tests see redacted 5xx responses (Internal Server Error) unlessNODE_ENV=development.
New in 0.5.5
- Validation decorators in
@meghjs/core:IsString,MinLength,ValidateNested,Type,Transformand more, with class-validator's names, options and messages. Each DTO is compiled once, so validating a request is several times faster. Switching a DTO is a change of import; class-validator DTOs keep working. AlsovalidateDto(). experimental.compiledValidation(orMEGH_COMPILED_VALIDATION=1) speeds up class-validator DTOs with the same results.validatoris an optional peer dependency, needed only for@IsUUID,@IsUrland@IsEmailwith options.- Error handling: exception filters,
@Catch,@UseFilters,app.useErrorHandler(),app.useErrorLogger()and more HTTP exception classes. - Inline routes get
mapPatch, the authentication handler, and.authorized(), and they sendResultswith their status. app.run(port, { host, onListen, shutdownTimeout }).MEGH_DOTENV=falseskips loading.envon import.- Health checks:
app.useHealth()serves/healthand/ready; Megh ORM registers adatabasecheck. - Request IDs: an
x-request-idon every response,reqIdon every log line, andgetRequestId().
Fixes in 0.5.5
useScheduler({ path })no longer crashesrun().@UploadFileand@UploadFilesreceive the saved files.@All()registers every method instead of crashing.- Framework errors keep their status (400 bad JSON, 413, 415, 429).
- A failing socket listener is logged instead of crashing the process.
- Two controllers with the same class name no longer share route metadata.
- Shutdown closes the cache, exits with code 1 on failure, and gives up after
shutdownTimeout. .envis parsed once instead of on everyEnvironment.get().- Inline route middleware classes are called with
thisbound.
New in 0.5.4
- Tables and models from templates.
npx megh make:model Product --template ecommerce/product(ormake:resource) writes the create-table migration and the model (or the whole REST resource). Tables its foreign keys point to are created too.--fields "title,price:money,status:in(draft|live)"describes a table on the command line, with presets such asslug,priceandaddress. See Templates and Fields. - Business domains.
npx megh scaffold:domain ecommerce(sc:domain) scaffolds a domain's tables at once. There are 11 domains: common, e-commerce, POS, medical, construction, marketing, real estate, HR, CRM, education and logistics. Add your own in.megh/templates/. See Domains. - Auth.
npx megh scaffold:auth(sc:auth) adds sign-up and sign-in with JWTs, API keys or both, and optionally roles and permissions: the tables, password hashing,AppAuthentication,AppAuthorization, anAuthControllerand a roles seeder, registered insrc/app.ts. See Auth. - RBAC.
npx megh scaffold:rbac(sc:rbac) adds roles (one or many per user) and permissions, checked with@Authorized({ roles })and@Authorized({ permissions }). See RBAC. megh template:list(templates) lists the templates.- SQL Server-safe foreign keys. On SQL Server, scaffolded migrations avoid the "may cause cycles or multiple cascade paths" error and write
restrictasNO ACTION. See SQL Server.
Fixes in 0.5.4
@Query()parameters are documented. A@Query()DTO and@Query('key')parameters were missing from the OpenAPI document. Each DTO property and each key is now a query parameter, with its type and constraints. See Query parameters.
New in 0.5.3
- Seeders.
npx megh make:seeder userswrites a seeder, andnpx megh db:seed(ormegh migrate --seed) runs them in one transaction, so a failing seeder saves nothing. See Seeding and Factories. - Factories with Faker.
defineFactory(User, ({ faker }) => ({ … }))builds rows with fake values, andnpx megh make:factory userwrites one from the model's columns. Install Faker to use them:npm i -D @faker-js/faker. See Factories. megh update:model. After an alter-table migration, it brings a model's column fields up to date and keeps relations and methods. See Updating a model.- Relation fields typed with the model. Write
@BelongsTo(() => Role) role?: Role | nullandposts?: Post[]instead ofBelongsTo<Role>andHasMany<Post>, which still work. See Relations. - Documented responses.
@ApiResponse(200, User)documents a response with a model or DTO,Paginated(User)a page, and Megh adds the400,401and403a route can return.make:resourcewrites them. See Responses. - Typed OpenAPI options.
OpenApiUiOptionstypes every option, including Swagger UI's settings, andauth: 'bearer'marks@Authorizedroutes. See Securing routes.
Fixes in 0.5.3
- Creating rows works on SQL Server.
create(),save()andinsertGetId()saved the row, then failed withValidation failed for parameter '1'. Invalid number.They now return the row withOUTPUT inserted.*. - SQL Server shows the real error. A failing migration or transaction could report
The ROLLBACK TRANSACTION request has no corresponding BEGIN TRANSACTIONinstead of what went wrong, for example a foreign key to a table that doesn't exist. dropColumn()works on SQL Server for columns with a default.- Optional relation fields are relations. A field such as
role?: BelongsTo<Role>was treated as a column, socreate()accepted it andwith('role')didn't type-check. - The route decorators'
openapioption is read.@Get('/', { openapi: { … } })was ignored.
Changes to note in 0.5.3
make:modelwrites the column type on nullable columns (@Column({ nullable: true, type: "string" })), so OpenAPI can document them. Runningupdate:modeladds it to fields it generated before.- Migrations'
table.string("name", 20)is read asvarchar(20), somake:resourceDTOs now get@MaxLength(20). OpenApiResponse()is deprecated: it documents a{ code, status, data }wrapper that Megh doesn't send. Use@ApiResponse().- Code that passed a relation to
create()orfill()through an optional marker field now fails to compile, as it should.
Fixes in 0.5.2
@UseMiddleware(SomeClass)works. Passing a middleware class to@UseMiddlewareon a controller or route crashedapp.run()withFunction is not registered. Classes are now resolved through the DI container, so they can use constructor injection. The@UseMiddleware(new SomeClass())workaround still works. See Middleware.- Paging works on SQL Server.
limit(),offset(),first(),find(),exists(),paginate(),simplePaginate()andforPage()failed withIncorrect syntax near 'limit'. Queries now usetop(n)andoffset … fetch next … rows onlyon SQL Server. See Paging on SQL Server.
Changes in 0.5.1
Connect with useMeghORM()
Megh now creates the database connection itself. Kysely ships with @meghjs/core, so an app only installs the driver for its database.
// Before (0.5.0)
import { db } from "./database/connection";
app.useDatabase(db);
// After (0.5.1+)
app.useMeghORM(); // reads DATABASE_URL, or pass { dialect, host, ... }- Put the connection in
.env, for exampleDATABASE_URL=postgres://app:secret@localhost:5432/app. Connecting lists every option and variable. - Replace
app.useDatabase(db)withapp.useMeghORM(). - Delete
src/database/connection.ts, and a"database"path under"megh"inpackage.jsonif you set one. While that file exists,megh migratekeeps using it; once it's gone, migrations connect fromDATABASE_URLtoo. - Uninstall
kyselyunless your own code imports it.
app.useDatabase(db) still works in 0.5.x and logs a deprecation warning.
Models with decorators
Models can describe their table with decorators. Models written with static table and hasMany(() => Post) keep working, so move them over when it suits you.
@Table("users")
export class User extends Model {
@PrimaryKey() @AutoIncrement() id?: number;
@Column({ unique: true }) email!: string;
@Column({ name: "display_name" }) displayName!: string;
@CreatedAt() createdAt?: Date;
@HasMany(() => Post) posts!: HasMany<Post>;
}- Fields marked
?are optional increate(). @Column({ name }), oruseMeghORM({ naming: 'snake_case' }), maps camelCase properties to other column names. See Column names.npx megh make:modelnow writes decorator models.
Migrations with the schema builder
npx megh make:migration now writes migrations with Megh's schema builder, which picks the right SQL type for each database:
export default defineMigration({
async up(schema) {
await schema.create("users", (table) => {
table.id();
table.string("email").unique();
table.timestamps();
});
},
async down(schema) {
await schema.dropIfExists("users");
},
});Existing Kysely migrations (export async function up(db)) still run, in order with the new ones.
The DB query builder
For queries that don't need a model:
import { DB } from "@meghjs/core";
const ids = await DB.table("users").where("active", true).pluck("id");
await DB.transaction(async () => {
/* ... */
});See Query builder.
Megh's own DI container
typedi is no longer a dependency. MeghContainer, @Injectable(), Token and inject() keep their API, and inject() now also works in field initializers:
@Injectable()
class UserService {
private readonly users = inject(UserRepository);
private readonly mailer = inject(Mailer, { optional: true });
}If your app imported typedi directly, switch to MeghContainer or add typedi to your own dependencies. Missing services and dependency cycles now fail with the full constructor chain in the error. See Dependency Injection.
megh new
New projects can include the ORM: pick MeghORM from the features, or pass --database postgres|mysql|sqlite|mssql.