In NocoBase, each request generates a ctx object, which is an instance of Context. Context encapsulates request and response information while providing NocoBase-specific functionality, such as database access, cache operations, permission management, internationalization, and logging.
NocoBase's Application is based on Koa, so ctx is essentially a Koa Context, but NocoBase extends it with rich APIs, allowing developers to conveniently handle business logic in Middleware and Actions. Each request has an independent ctx, ensuring data isolation and security between requests.
ctx.action provides access to the Action being executed for the current request. Includes:
Internationalization (i18n) support.
ctx.i18n provides locale informationctx.t() is used to translate strings based on languagectx.db provides an interface for database access, allowing you to directly operate on models and execute queries.
ctx.cache provides cache operations, supporting reading from and writing to the cache, commonly used to accelerate data access or save temporary state.
ctx.app is the NocoBase application instance, allowing access to global configuration, plugins, and services.
ctx.auth.user retrieves the currently authenticated user's information, suitable for use in permission checks or business logic.
ctx.state is used to share data in the middleware chain.
ctx.logger provides logging capabilities, supporting multi-level log output.
ctx.permission is used for permission management, ctx.can() is used to check whether the current user has permission to execute a certain operation.
ctx objectctx is an extension of Koa Context, integrating NocoBase functionalityctx.db, ctx.cache, ctx.auth, ctx.state, ctx.logger, ctx.can(), ctx.t(), etc.ctx in Middleware and Actions allows for convenient handling of requests, responses, permissions, logs, and the database