xiaohongshu
xiaohongshu
add-resource-events
Add real-time event emission to a resource service. Use when adding SSE/real-time capabilities to a resource. Triggers on "add events", "real-time events", "SSE events".
Full skill instructions
Enables real-time event emission for a resource service via Server-Sent Events (SSE).
Event Infrastructure:
src/events/event-emitter.ts - Singleton AppEventEmittersrc/events/base.service.ts - BaseService with emitEvent()src/schemas/event.schema.ts - Event type definitionssrc/routes/events.router.ts - SSE endpointEvent Pattern: {serviceName}:{action} (e.g., notes:created, notes:updated)
To add events to a resource:
BaseService (see create-resource-service)AuthorizationService// src/events/base.service.ts
export abstract class BaseService {
constructor(protected serviceName: string) {}
protected emitEvent<T>(
action: ServiceEventType["action"],
data: T,
options?: {
id?: string;
user?: { userId: string; [key: string]: unknown };
},
) {
appEvents.emitServiceEvent(this.serviceName, {
id: options?.id || uuidv4(),
action,
data,
user: eventUser,
timestamp: new Date(),
resourceType: this.serviceName,
});
}
}
export class NoteService extends BaseService {
constructor(...) {
super("notes"); // Service name for event routing
}
async create(data, user) {
// ... create logic ...
this.emitEvent("created", note, { id: note.id, user });
return note;
}
async update(id, data, user) {
// ... update logic ...
this.emitEvent("updated", updatedNote, { id: updatedNote.id, user });
return updatedNote;
}
async delete(id, user) {
// ... delete logic ...
this.emitEvent("deleted", note, { id: note.id, user });
return true;
}
}
// src/routes/events.router.ts
appEvents.on("notes:created", eventHandler);
appEvents.on("notes:updated", eventHandler);
appEvents.on("notes:deleted", eventHandler);
Your service must extend BaseService:
import { BaseService } from "@/events/base.service";
export class {Entity}Service extends BaseService {
constructor(...) {
super("{entities}"); // Plural for event namespace
}
}
Add emitEvent() calls after successful operations:
async create(data, user) {
const {entity} = await this.repository.create(data, user.userId);
this.emitEvent("created", {entity}, { id: {entity}.id, user });
return {entity};
}
async update(id, data, user) {
const updated = await this.repository.update(id, data);
if (!updated) return null;
this.emitEvent("updated", updated, { id: updated.id, user });
return updated;
}
async delete(id, user) {
const {entity} = await this.repository.findById(id);
const deleted = await this.repository.remove(id);
if (deleted) {
this.emitEvent("deleted", {entity}, { id: {entity}.id, user });
}
return deleted;
}
In src/services/authorization.service.ts:
async canReceive{Entity}Event(
user: AuthenticatedUserContextType,
{entity}Data: { createdBy: string; [key: string]: unknown },
): Promise<boolean> {
if (this.isAdmin(user)) return true;
if ({entity}Data.createdBy === user.userId) return true;
return false;
}
In src/routes/events.router.ts, add listeners:
// Listen to {entity} events
appEvents.on("{entities}:created", eventHandler);
appEvents.on("{entities}:updated", eventHandler);
appEvents.on("{entities}:deleted", eventHandler);
Update the shouldUserReceiveEvent function:
async function shouldUserReceiveEvent(
event: ServiceEventType,
user: AuthenticatedUserContextType,
authorizationService: AuthorizationService,
): Promise<boolean> {
switch (event.resourceType) {
case "notes":
// ... existing ...
case "{entities}":
if (
typeof event.data === "object" &&
event.data !== null &&
"createdBy" in event.data
) {
return await authorizationService.canReceive{Entity}Event(
user,
event.data as { createdBy: string; [key: string]: unknown },
);
}
return false;
default:
return false;
}
}
In src/schemas/event.schema.ts:
export const {entity}EventSchema = serviceEventSchema.extend({
data: z.object({
id: z.string(),
// ... entity-specific fields
createdAt: z.date().optional(),
updatedAt: z.date().optional(),
}),
});
export type {Entity}EventType = z.infer<typeof {entity}EventSchema>;
1. Client: POST /notes (create a note)
2. Controller: calls NoteService.create()
3. Service: creates note, calls this.emitEvent("created", note, ...)
4. BaseService: appEvents.emitServiceEvent("notes", { action: "created", ... })
5. EventEmitter: emits "notes:created" event
6. Events Router: catches event, checks authorization
7. SSE Stream: sends to authorized clients
8. Client: receives { event: "notes:created", data: {...} }
const eventSource = new EventSource("/events", {
headers: { Authorization: `Bearer ${token}` },
});
eventSource.addEventListener("notes:created", (event) => {
const data = JSON.parse(event.data);
console.log("New note:", data);
});
eventSource.addEventListener("notes:updated", (event) => {
const data = JSON.parse(event.data);
console.log("Updated note:", data);
});
eventSource.addEventListener("notes:deleted", (event) => {
const data = JSON.parse(event.data);
console.log("Deleted note:", data);
});
create-resource-service - Creating services with event emissioncreate-routes - Events router exampletest-resource-service - Testing event emissionxiaohongshu
technical spec
product ux expert
database patterns
Conduct multi-agent task orchestration and workflow coordination.
Initialize project with Conductor artifacts (product definition,
Expert in web animations, transitions, and motion design using Framer Motion and CSS
Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...
PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.
Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...
Display project status, active tracks, and next actions
Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.
Generate, edit, and beat-sync AI video with leading models in one workspace.
The world's fastest calendar for remote work
Transform Your Design with AI Designer by ImgCreator.ai
Revolutionizing Video Production with AI-Powered Creativity
Extend an image past the frame and let AI fill the new aspect ratio.
Discover your celebrity doppelgänger with StarByFace!
ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.
Opus.ai: Revolutionize Your Web Experience