xiaohongshu
xiaohongshu
fn-args-deps
Enforce the fn(args, deps) pattern: functions over classes with explicit dependency injection
Full skill instructions
All business logic functions MUST follow this signature:
fn(args, deps)
args and deps have different lifetimes:
args are per-call datadeps are long-lived collaboratorsKeeping them separate makes dependency bloat visible and composition easier.
ALWAYS declare explicit deps types for each function:
// CORRECT
type GetUserDeps = {
db: Database;
logger: Logger;
};
async function getUser(
args: { userId: string },
deps: GetUserDeps
): Promise<User | null> {
deps.logger.info(`Getting user ${args.userId}`);
return deps.db.findUser(args.userId);
}
// WRONG - God object with all deps
async function getUser(
args: { userId: string },
deps: AllServiceDeps // Contains mailer, cache, metrics that getUser doesn't use
): Promise<User | null>
Classes become problematic when:
this// WRONG
class UserService {
constructor(
private db: Database,
private logger: Logger,
private mailer: Mailer, // only createUser needs this
private cache: Cache, // only someOtherMethod needs this
) {}
}
// CORRECT
type GetUserDeps = { db: Database; logger: Logger };
type CreateUserDeps = { db: Database; logger: Logger; mailer: Mailer };
Wire deps ONCE at the boundary, not at every call site:
// user-service/index.ts
export function createUserService({ deps }: { deps: UserServiceDeps }) {
return {
getUser: ({ userId }: { userId: string }) =>
getUser({ userId }, deps),
createUser: ({ name, email }: { name: string; email: string }) =>
createUser({ name, email }, deps),
};
}
// main.ts (Composition Root)
const deps = { db, logger, mailer };
const userService = createUserService({ deps });
// Handlers stay clean
await userService.getUser({ userId: '123' });
When you have many related functions (5+), choose one approach per module:
Approach 1: Inject Individually (default)
Use when most consumers only need 1–2 functions:
// user-functions.ts
export async function getUser(args: { userId: string }, deps: GetUserDeps) { ... }
export async function createUser(args: { name: string; email: string }, deps: CreateUserDeps) { ... }
export type GetUserFn = typeof getUser;
export type CreateUserFn = typeof createUser;
// notification-handler.ts — only needs sendWelcomeEmail
export type NotificationHandlerDeps = {
sendWelcomeEmail: SendWelcomeEmailFn;
// doesn't need getUser or createUser
};
Approach 2: Inject as Grouped Object (when they travel together)
Use when functions form a cohesive module and consumers inject the same set:
// user-functions.ts
export const userFns = {
getUser,
createUser,
updateUser,
deleteUser,
sendWelcomeEmail,
} as const;
export type UserFns = typeof userFns;
// user-router.ts — needs most user functions
export type UserRouterDeps = {
userFns: UserFns;
};
Rule of thumb: Default to injecting individually. Group only when functions genuinely travel together. If grouping feels like a "god object", split it.
Only inject things that hit network, disk, or clock. Import pure utilities directly:
// WRONG - Over-injecting
function createUser(args, deps: { db, logger, slugify, randomUUID }) { }
// CORRECT - Only inject what you'll mock
import { slugify } from 'slugify';
import { randomUUID } from 'crypto';
function createUser(args, deps: { db, logger }) { }
Use import type to prevent runtime coupling:
// CORRECT
import type { Mailer } from '../infra/mailer';
// WRONG - Runtime import creates coupling
import { mailer } from '../infra/mailer';
import { describe, it, expect } from 'vitest';
import { mock } from 'vitest-mock-extended';
import { getUser, type GetUserDeps } from './get-user';
it('returns user when found', async () => {
const mockUser = { id: '123', name: 'Alice', email: '[email protected]' };
const deps = mock<GetUserDeps>();
deps.db.findUser.mockResolvedValue(mockUser);
const result = await getUser({ userId: '123' }, deps);
expect(result).toEqual(mockUser);
});
import { mailer as _mailer, type Mailer } from '../infra/mailer';
const defaultDeps: SendEmailDeps = { mailer: _mailer };
export async function sendEmail(
recipient: User,
sender: User,
deps: SendEmailDeps = defaultDeps // Default for existing callers
) { ... }
import type { Mailer } from '../infra/mailer';
export async function sendEmail(
recipient: User,
sender: User,
deps: SendEmailDeps // No default - must inject
) { ... }
export async function sendEmail(
args: { recipient: User; sender: User },
deps: SendEmailDeps
) { ... }
Classes are fine for:
| Use Case | Why It's OK |
|---|---|
| Framework integration | NestJS, Express middleware require class syntax |
| Stateful resources | Connection pools, caches with lifecycle |
| Builder patterns | Fluent APIs where method chaining adds clarity |
| Thin wrappers | Delegating to pure functions (see below) |
Classes are NOT OK for:
Use classes as thin wrappers, keep logic in pure functions:
// Pure function - your actual logic
async function createUser(
args: CreateUserInput,
deps: { db: Database; logger: Logger }
): Promise<Result<User, 'EMAIL_EXISTS' | 'DB_ERROR'>> {
// Business logic here
}
// NestJS wrapper - thin delegation layer
@Injectable()
export class UserService {
constructor(private db: Database, private logger: Logger) {}
async createUser(args: CreateUserInput) {
return createUser(args, { db: this.db, logger: this.logger });
}
}
Critics sometimes worry that creating many small objects (args objects, deps bags, factory functions) increases garbage collection pressure.
The reality: Modern V8 engines (Orinoco) use generational garbage collection. Objects that die young—like the temporary objects created during request handling—are reclaimed almost instantly. V8 is extremely efficient at this.
For I/O-bound web applications:
| Operation | Typical Latency |
|---|---|
| Database query | 1-50ms |
| HTTP request | 10-500ms |
| Object allocation | 0.0001ms |
The database query is 10,000-500,000x slower than object allocation. The architectural clarity and type safety of the fn(args, deps) pattern far outweigh any micro-overhead.
When to worry about allocation:
For typical web services, don't optimize for GC. Optimize for correctness, testability, and maintainability.
Enable in tsconfig.json:
{
"compilerOptions": {
"verbatimModuleSyntax": true
}
}
ESLint rule to prevent infra imports:
"no-restricted-imports": ["error", {
patterns: [{
group: ["**/infra/**"],
message: "Domain code must not import from infra. Inject dependencies instead."
}]
}]
xiaohongshu
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