fiberx-backend-toolkit
v1.0.6
Published
A TypeScript backend toolkit providing shared domain logic, infrastructure helpers, and utilities for FiberX server-side applications and services.
Readme
FiberX Backend Toolkit
Shared TypeScript backend utilities for FiberX services. The package includes Sequelize connection helpers, schema-driven migration generation, migration and seeder runners, Express middleware, storage helpers, mailer processors, RBAC loading, validators, and common utilities.
Requirements
- Node.js 20.x
- TypeScript projects using CommonJS or transpiled output
- Sequelize v6
- A project-level environment file in
environment_variables/
Installation
npm install fiberx-backend-toolkitQuality Commands
npm run typecheck
npm run lint
npm run format:check
npm run spell:check
npm run build
npm run checkUse npm run format to apply Prettier formatting locally. The CI workflow runs type checking, linting, formatting checks, spell checking, and the build on every push and pull request.
Import Paths
import { LoggerUtil, EnvManagerUtil } from "fiberx-backend-toolkit/utils";
import { SequelizeConnector, MigrationRunnerScript } from "fiberx-backend-toolkit/database";
import { AuthenticationMiddleWare } from "fiberx-backend-toolkit/middle-ware";
import type { SchemaDefinitionInterface } from "fiberx-backend-toolkit/types";The root package also re-exports the public modules:
import { SequelizeConnector, LoggerUtil } from "fiberx-backend-toolkit";Environment Configuration
By default, the toolkit reads YAML files from:
environment_variables/The file is selected from process.env.MODE:
development -> development_env.yaml
staging -> staging_env.yaml
production -> production_env.yamlExample:
MODE: development
DB_DIALECT: postgres
DB_HOST: localhost
DB_PORT: 5432
DB_NAME: fiberx_app
DB_USER: postgres
DB_PASSWORD: postgres
DB_LOGGING: falseFor compatibility, the previous misspelled environment_variables/ directory is still read if the corrected directory is not present.
Database Connection
Use SequelizeConnector.getInstance() rather than constructing the connector directly.
import { SequelizeConnector } from "fiberx-backend-toolkit/database";
const connector = SequelizeConnector.getInstance();
const sequelize = await connector.connect({
name: "default",
dialect: "postgres",
database: "fiberx_app",
username: "postgres",
password: "postgres",
host: "localhost",
port: 5432,
logging: false,
});connect() authenticates and attempts database creation for supported SQL dialects. connectSync() only creates a Sequelize instance and is useful when model files need to be initialized before application bootstrap.
Directory Convention
The generator and runner scripts expect these project-root paths:
src/database/
schemas/
schema_snapshots/
models/
migrations/
seeders/Missing directories are created where the scripts need them.
Schema Definitions
Schemas are plain TypeScript files with a default export:
import { DataTypes } from "sequelize";
import type { SchemaDefinitionInterface } from "fiberx-backend-toolkit/types";
const UserSchema: SchemaDefinitionInterface = {
connection_name: "default",
database_name: "public",
migration_priority: 1,
table_name: "users",
model_name: "User",
timestamps: true,
columns: {
id: {
type: DataTypes.BIGINT,
primaryKey: true,
autoIncrement: true,
allowNull: false,
},
email: {
type: DataTypes.STRING(255),
allowNull: false,
unique: true,
},
},
indexes: [{ name: "users_email_unique", fields: ["email"], unique: true }],
};
export default UserSchema;You can scaffold a schema:
import { CreateSchemaScript } from "fiberx-backend-toolkit/database";
new CreateSchemaScript("User").run();Migration Workflow
Generate migrations from schema changes:
import { MakeMigrationsScript } from "fiberx-backend-toolkit/database";
new MakeMigrationsScript().run();Run migrations:
import { MigrationRunnerScript } from "fiberx-backend-toolkit/database";
await new MigrationRunnerScript().run("up");Rollback migrations:
await new MigrationRunnerScript().run("down");Run a specific migration file:
await new MigrationRunnerScript().run("up", undefined, "1_20260515120000_create_table_users.ts");Migration runner behavior:
- Tracks applied migrations in
sequelize_database_tables_meta. - Supports both
.tsand.jsmigration files and ignores.d.ts. - Uses dialect-safe quoting for metadata reads.
- Sorts by numeric migration priority, then filename.
- Runs toolkit-generated migrations and metadata updates in a Sequelize transaction.
- Skips already-applied migrations on
upand skips unapplied migrations ondown.
When running TypeScript migration files directly, execute your script with ts-node and tsconfig-paths/register so path aliases resolve.
node -r ts-node/register -r tsconfig-paths/register ./scripts/migrate.tsModel Generation
Generate Sequelize model files from schemas:
import { SequelizeModelGeneratorScript } from "fiberx-backend-toolkit/database";
new SequelizeModelGeneratorScript().generateModelsFromSchemas();The old misspelled SeqeulizeModelGeneratorScript export is still available for compatibility.
Seeders
Create and run seeders:
import { CreateSeederScript, SeederRunnerScript } from "fiberx-backend-toolkit/database";
new CreateSeederScript("User", "initial_users").run();
await new SeederRunnerScript().run("up");
await new SeederRunnerScript().run("down", "user");Seeder state is tracked in sequelize_database_table_seeder_meta.
Express Middleware
import { AuthenticationMiddleWare } from "fiberx-backend-toolkit/middle-ware";
const auth = new AuthenticationMiddleWare({
extractRequestInfoMethod: async (req) => ({
access_token: req.headers.authorization ?? null,
refresh_token: null,
origin_url: req.headers.origin ?? "",
request_id: String(req.headers["x-request-id"] ?? ""),
}),
validateActorHasPermissionMethod: async (requestInfo) => {
return requestInfo.permission_name === "user.read";
},
});
app.get("/users", auth.setPermissionName("user.read"), handler);AuthenticationMiddleWare is the corrected export. The previous AuthenicationMiddleWare export remains available for existing services.
Utility Modules
import {
LoggerUtil,
EnvManagerUtil,
InputValidatorUtil,
InputTransformerUtil,
SafeExecuteUtil,
UUIDGeneratorUtil,
EncryptorDecryptorUtil,
TOTPServiceUtil,
} from "fiberx-backend-toolkit/utils";Build
npm run buildThe build emits CommonJS JavaScript and declarations to dist/.
Notes
- Generated migrations accept an optional third argument for transaction options.
- Existing older migrations still run, but only generated or manually transaction-aware migrations can fully participate in the runner transaction.
- Avoid
sequelize.sync({ alter: true })in production services that use these migration scripts. Treat schema files as the source for migration generation, and treat migration files as the auditable database history. - updated the code
License
ISC
