Context
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 additional APIs, allowing you to conveniently handle business logic in Middleware and Actions. Each request has an independent ctx, ensuring data isolation between requests.
ctx.action
ctx.action provides information about the Action being executed for the current request, including:
- ctx.action.params
- ctx.action.actionName
- ctx.action.resourceName
ctx.i18n & ctx.t()
Internationalization (i18n) support.
ctx.i18nprovides locale informationctx.t()is used to translate strings based on language
ctx.db
ctx.db provides an interface for database access, allowing you to directly operate on models and execute queries.
ctx.cache
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
ctx.app is the NocoBase application instance, allowing access to global configuration, plugins, and services.
ctx.auth.user
ctx.auth.user retrieves the currently authenticated user's information, suitable for use in permission checks or business logic.
ctx.state.currentRoles
ctx.state is used to share data in the middleware chain.
ctx.logger
ctx.logger provides logging capabilities, supporting multi-level log output.
ctx.permission & ctx.can()
ctx.permission is used for permission management, ctx.can() is used to check whether the current user has permission to execute a certain operation.
Summary
- Each request corresponds to an independent
ctxobject ctxis an extension of Koa Context, integrating NocoBase functionality- Common properties include:
ctx.db,ctx.cache,ctx.auth,ctx.state,ctx.logger,ctx.can(),ctx.t(), etc. - Using
ctxin Middleware and Actions allows for convenient handling of requests, responses, permissions, logs, and the database
Related Links
- Middleware — Full workflow of using
ctxto handle requests in middleware - ResourceManager — Source and definition of
ctx.actionin resource Actions - ACL — Permission checking mechanism for
ctx.permissionandctx.can() - Cache — Detailed usage of
ctx.cachefor cache operations - Logger — Logging and output configuration for
ctx.logger - i18n — Internationalization support for
ctx.t()andctx.i18n

