| name | sparc-refinement-example-1-performance-optimization |
| description | Sub-skill of sparc-refinement: Example 1: Performance Optimization (+2). |
| version | 1.0.0 |
| category | development |
| type | reference |
| scripts_exempt | true |
Example 1: Performance Optimization (+2)
Example 1: Performance Optimization
async function getUserPermissions(userId: string): Promise<string[]> {
const user = await db.query('SELECT * FROM users WHERE id = ?', [userId]);
const roles = await db.query('SELECT * FROM user_roles WHERE user_id = ?', [userId]);
const permissions = [];
for (const role of roles) {
const perms = await db.query('SELECT * FROM role_permissions WHERE role_id = ?', [role.id]);
permissions.push(...perms);
}
return permissions;
}
async function getUserPermissions(userId: string): Promise<string[]> {
const cached = await cache.get(`permissions:${userId}`);
if (cached) return cached;
const permissions = await db.query(`
SELECT DISTINCT p.name
FROM users u
JOIN user_roles ur ON u.id = ur.user_id
JOIN role_permissions rp ON ur.role_id = rp.role_id
JOIN permissions p ON rp.permission_id = p.id
WHERE u.id = ?
`, [userId]);
await cache.set(`permissions:${userId}`, permissions, 300);
return permissions;
}
Example 2: Error Handling
export class AppError extends Error {
constructor(
message: string,
public code: string,
public statusCode: number,
public isOperational = true
) {
super(message);
Object.setPrototypeOf(this, new.target.prototype);
Error.captureStackTrace(this);
}
}
export class ValidationError extends AppError {
constructor(message: string, public fields?: Record<string, string>) {
super(message, 'VALIDATION_ERROR', 400);
}
}
export class AuthenticationError extends AppError {
constructor() {
(message, , );
}
}
(): {
(error && error.) {
res.(error.).({
: {
: error.,
: error.,
...(error && { : error. })
}
});
} {
logger.(, { error, : req });
res.().({
: {
: ,
:
}
});
}
}
Example 3: Circuit Breaker Pattern
export class CircuitBreaker {
private failures = 0;
private lastFailureTime?: Date;
private state: 'CLOSED' | 'OPEN' | 'HALF_OPEN' = 'CLOSED';
constructor(
private threshold = 5,
private timeout = 60000
) {}
async execute<T>(operation: () => Promise<T>): Promise<T> {
if (this.state === 'OPEN') {
if (this.shouldAttemptReset()) {
this.state = 'HALF_OPEN';
} else {
throw new Error('Circuit breaker is OPEN');
}
}
try {
const result = await operation();
this.onSuccess();
return result;
} catch (error) {
this.();
error;
}
}
(): {
. = ;
. = ;
}
(): {
.++;
. = ();
(. >= .) {
. = ;
}
}
(): {
.
&& (.() - ..()) > .;
}
}