Model Hooks
Noblex supports powerful hooks to run code before or after database operations, or to transform responses dynamically.
Here’s an example of how to use hooks with the blogPosts
collection:
import { Hooks, PreHook, PostHook, JsonHook } from "noblex";
import type { Request } from "noblex";
@Hooks("blogPosts")
class BlogPostsHooks {
@JsonHook()
static transformResponse(req: Request, doc: any, ret: any) {
delete ret.createdAt;
delete ret.updatedAt;
return ret;
}
@PreHook("find", "findOne")
static preFind(req: Request, ctx: any) {
console.log("Running before find or findOne queries");
}
@PostHook("find")
static postFind(req: Request, result: any[]) {
console.log("After fetching blogPosts:", result.length, "items");
}
}
export default BlogPostsHooks;
What’s happening here?
-
@Hooks("blogPosts")
: attaches hooks to theblogPosts
collection. -
@JsonHook()
: modifies the JSON response, removingcreatedAt
andupdatedAt
. -
@PreHook
: runs beforefind
andfindOne
operations. -
@PostHook
: runs afterfind
operations. -
All hooks receive the current
Request
object (req
), so you can implement RBAC or logging easily.
Hook Import Order
Make sure to import all your hooks before creating the database connection.
import "./modules/blogPosts/blogPosts.hooks.js";
defaultDB({
uri: `mongodb://${env.DB_HOST}:${env.DB_PORT}/${env.DB_NAME}`,
// other options...
});