@dharayush7/fireclass-js
v2.0.9
Published
Type-safe Firestore ODM for Node.js and Express using Firebase Admin, with validated models, typed CRUD and queries, and error middleware.
Maintainers
Keywords
Readme
@dharayush7/fireclass-js binds the shared Fireclass model API to firebase-admin/firestore. Use it in Node.js servers, Express applications, workers, Cloud Functions, and other trusted server runtimes.
Server-only package: Firebase Admin bypasses client Firestore Security Rules. Never import this package into browser code or expose service-account values to clients.
Prerequisites
- Node.js application with TypeScript decorators enabled.
- Firebase project with Firestore enabled.
- Application Default Credentials or Firebase Admin service-account values.
- A gitignored environment file or managed secret store for private keys.
Installation
npm install @dharayush7/fireclass-js firebase-admin class-validator class-transformer reflect-metadataEnable decorators:
{
"compilerOptions": {
"module": "NodeNext",
"moduleResolution": "NodeNext",
"experimentalDecorators": true,
"emitDecoratorMetadata": true
}
}Firebase Admin setup
Store credentials outside source control:
PROJECT_ID=your-project-id
CLIENT_EMAIL=firebase-adminsdk-xxxxx@your-project-id.iam.gserviceaccount.com
PRIVATE_KEY="-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----\n"Create a memoized Firebase entry:
// src/lib/firebase.ts
import "dotenv/config";
import { cert, getApps, initializeApp } from "firebase-admin/app";
import { getFirestore, type Firestore } from "firebase-admin/firestore";
export function getDb(): Firestore {
if (getApps().length === 0) {
initializeApp({
credential: cert({
projectId: process.env.PROJECT_ID,
clientEmail: process.env.CLIENT_EMAIL,
privateKey: process.env.PRIVATE_KEY?.replace(/\\n/g, "\n"),
}),
});
}
return getFirestore();
}Create the application binding:
// src/lib/fireclass.ts
import "reflect-metadata";
import { createFireclass } from "@dharayush7/fireclass-js";
import { getDb } from "./firebase.js";
export const { BaseModel, adapter } = createFireclass(getDb());The local Fireclass file should export initialized values only. Import decorators, query types, errors, and middleware directly from this package where they are used.
Define a model
// src/models/user.ts
import { Collection } from "@dharayush7/fireclass-js";
import { IsEmail, IsInt, IsString, Length, Min } from "class-validator";
import { BaseModel } from "../lib/fireclass.js";
@Collection("users")
export class User extends BaseModel<User> {
@IsString()
@Length(2, 80)
name!: string;
@IsEmail()
email!: string;
@IsInt()
@Min(0)
age!: number;
constructor(data?: Partial<User>) {
super(data);
Object.assign(this, data);
}
}CRUD and typed queries
const id = await new User({
name: "Ada Lovelace",
email: "[email protected]",
age: 36,
}).save();
const user = await User.findById(id);
const adults = await User.findMany({
where: { age: { gte: 18 } },
orderBy: { name: "asc" },
limit: 20,
});
if (user) {
user.age = 37;
await user.save();
await user.delete();
}Model instances provide save() and delete(). Model classes provide findById, findMany, findOne, count, deleteById, and deleteMany.
Supported query operators are equals, gt, gte, lt, lte, in, notIn, arrayContains, and arrayContainsAny, plus ordering, limits, and startAfter.
Export index
| Export | Purpose | | --- | --- | | createFireclass(db) | Return a bound BaseModel and AdminAdapter | | Fireclass | Return type of createFireclass | | getBaseModel(db) | Compatibility alias for the deprecated package | | AdminAdapter | Firebase Admin implementation of the core adapter | | fireclassErrorHandler(options?) | Express-compatible Fireclass error middleware | | FireclassErrorHandlerOptions | Middleware status-code options | | Core exports | Decorators, query types, validation, conversion, and errors |
createFireclass
function createFireclass(db: Firestore): {
BaseModel: BaseModelClass;
adapter: AdminAdapter;
};Create one binding and reuse it. Multiple calls create separate adapter and base-class identities even when they reference the same Firestore instance.
AdminAdapter
| Method | Firebase Admin operation | | --- | --- | | add | Collection add | | set | Document set with merge | | get | Document get | | query | Query get | | delete | Document delete | | batchDelete | Write batches of at most 500 deletes | | count | Aggregate count | | convert | Recursive Timestamp-to-Date conversion |
Realtime subscriptions are intentionally absent; browser realtime support lives in @dharayush7/fireclass-react.
Express error middleware
Register Fireclass error middleware after routes:
import express from "express";
import { fireclassErrorHandler } from "@dharayush7/fireclass-js";
const app = express();
app.use(express.json());
// Register application routes first.
app.use(
fireclassErrorHandler({
validationStatus: 422,
fireclassStatus: 400,
}),
);Both status options default to 400. Validation failures become:
{
"error": "ValidationError",
"message": "Validation failed for \"User\": email (email must be an email)",
"details": [
{
"property": "email",
"constraints": {
"isEmail": "email must be an email"
}
}
]
}Other Fireclass failures include their concrete error name and message. Non-Fireclass errors are passed to next(error) unchanged.
Migration from the deprecated package
- import { getBaseModel } from "@dharayush7/fireclass/core";
+ import { getBaseModel } from "@dharayush7/fireclass-js";getBaseModel(db) remains available as a migration alias. Prefer createFireclass(db) for new code because it also exposes the adapter. Replace legacy subpath imports with direct runtime imports:
import {
Collection,
ValidationFailedError,
type QueryOptions,
} from "@dharayush7/fireclass-js";See the complete legacy migration guide for changed errors, return values, and query capabilities.
CLI setup
After Firebase initialization exists, the CLI can create fireclass.json, the Fireclass binding, models, and decorator configuration:
npx fireclass init
npx fireclass doctorFor an Express factory export, configure getDb() so generated code calls the function.
Documentation and examples
- Express installation
- Complete Node/Express API
- Express CRUD guide
- Core model API
- Runnable Express application
See CHANGELOG.md for version history and RELEASE_NOTES.md for the current release summary.
License
MIT. Copyright Ayush Dhar.
