Introduction
Custom decorators
Write your own annotations that add guards, interceptors, route parameters or behaviour around a method.
NestJS builds most of its features out of decorators, and lets you write your own. Kest has the same four kinds. Because the processor reads the annotations while compiling, they cost nothing at run time.
| You want | Use | NestJS equivalent |
|---|---|---|
| Attach a guard, interceptor, pipe or filter, or readable metadata | @Guarded, @Intercepted, @Metadata on your annotation | SetMetadata, a guard that reads it |
| Several decorators under one name | put them on your annotation | applyDecorators |
| Compute a handler argument from the request | @ParamDecorator | createParamDecorator |
| Wrap any method (cache, retry, audit, time, trace) | @MethodAspect | an interceptor, for any provider method |
Attach metadata and a guard
@Guarded(RateLimitGuard::class)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
annotation class RateLimit(val perMinute: Int = 60)
@Injectable
class RateLimitGuard : Guard {
override suspend fun canActivate(ctx: ExecutionContext): Boolean {
val limit = ctx.annotation<RateLimit>()?.perMinute ?: return true // handler first, then the controller
return counter.allow(ctx.request.remoteAddress ?: "?", limit)
}
}
@RateLimit(perMinute = 10) @Post("/login") fun login(...) = ...@Metadata is the same without a guard (NestJS SetMetadata); @Intercepted(X::class) attaches an interceptor. Built in: @Role, @Roles, @CacheTtl, @Public.
Compose decorators
An annotation may carry other decorators. Everything written on it applies wherever it is used:
@UseGuards(JwtAuthGuard::class)
@Role("admin")
@UseInterceptors(AuditInterceptor::class)
@Target(AnnotationTarget.CLASS, AnnotationTarget.FUNCTION)
annotation class AdminOnly
@AdminOnly @Delete("/{id}") fun remove(@Param id: String) = ...@UseGuards, @UseInterceptors, @UseFilters, @UsePipes, @Version, @Role and @Roles can sit on an annotation, and so can your own @Guarded and @Metadata ones, to any depth.
Parameter decorators
@ParamDecorator(CurrentUserResolver::class)
@Target(AnnotationTarget.VALUE_PARAMETER)
annotation class CurrentUser(val required: Boolean = true)
class CurrentUserResolver : ParamResolver<CurrentUser> {
override fun resolve(annotation: CurrentUser, ctx: HttpContext): Any? =
ctx.principal ?: if (annotation.required) throw UnauthorizedException("Sign in first") else null
}
@Get("/me") fun me(@CurrentUser user: Principal) = userThe resolver comes from the container when it is a provider (so it can take dependencies); otherwise its no-argument constructor is used. The annotation's own arguments reach resolve. The kest g decorator current-user command writes this pair.
Built in, all of them ordinary parameter binders: @Param, @Query, @Header, @Cookie, @Ip, @Body, @Request, @Response, @FormFile, @Validated.
@Get("/search") fun search(@Query dto: SearchDto) // the whole query string as one validated object
@Post("/rename") fun rename(@Body("name") name: String) // one property of a JSON bodyMethod decorators
Mark your annotation with @MethodAspect and name the class that wraps the call:
@MethodAspect(AuditAspect::class)
@Target(AnnotationTarget.FUNCTION, AnnotationTarget.CLASS)
annotation class Audited(val action: String)
class AuditAspect(private val log: AuditLog) : AspectWrapper { // a provider, or any class with a no-argument constructor
override fun around(annotation: Annotation, call: MethodCall): Any? {
val a = annotation as Audited
try { return call.proceed() } finally { log.record(a.action, call.method, call.args.toList()) }
}
}
@Injectable
open class Orders { // open class, open methods
@Audited("order.cancel") open fun cancel(id: String) { ... }
}MethodCall carries the target, class and method names and the arguments; proceed() runs the real method (or the next aspect).
Several aspects nest in the order written, the first outermost, and @Transactional is always innermost. Class-level aspect annotations apply to every public method.
Built in
| Annotation | Does | Package |
|---|---|---|
@Async | runs the method on its own virtual thread; CompletableFuture results flow back, Unit is fire and forget | core |
@Retry(attempts, delayMillis, multiplier, maxDelayMillis, jitter, on, stopOn, statuses) | calls again when it fails, waiting longer each time, for calls outside the process | core |
@Transactional | runs in a transaction | orm |
@Cacheable, @CachePut, @CacheEvict | caches by arguments | cache |
@Timed, @Counted | metrics | metrics |
@Traced | an OpenTelemetry span | opentelemetry |
How it works, and the limits
For a class with aspect annotations the processor writes a subclass, <Class>_Tx, that overrides the decorated methods, and the generated module builds the subclass instead. There are no proxies and no reflection on the call path.
Limits
The class and the decorated methods must be open. A call from one method of a class to another method of the same instance does not pass through the aspect (the same as with Spring's proxies). Suspend functions, generic functions and varargs are rejected with a clear build error. Constructor parameters with default values are not supported on such a class.