@adonisjs/route-model-binding

中文文档
2.0.0-0发布于 2024/05/10MITTypeScriptES Module近 30 天下载 4842

Route model binding for AdonisJS

原始使用文档
文档目录12 节
  1. Introduction
  2. Setup
  3. Basic usage
  4. Changing the lookup key
  5. Change lookup key globally via model
  6. Change the lookup key for a single route.
  7. Change lookup logic
  8. Scoped params
  9. Customizing relationship lookup
  10. Unbound params
  11. Code of Conduct
  12. License

@adonisjs/route-model-binding


gh-workflow-image npm-image license-image

Introduction

Bind the route parameters with Lucid models and automatically query the database

Route model binding is a neat way to remove one-liner Lucid queries from your codebase and use conventions to query the database during HTTP requests.

In the following example, we connect the route params :post and :comments with the arguments accepted by the show method.

  • The value of the first param from the URL will be used to query the first typed hinted model on the show method (i.e., Post).
  • Similarly, the value of the second param will be used to query the second typed hinted model (i.e., Comment).

Note: The params and models are connected using the order they appear and not the name. This is because TypeScript decorators have no way to know the names of the arguments accepted by a method.

// Routes file
import router from '@adonisjs/core/services/router'

const PostsController = () => import('#controllers/posts_controller')

router.get('/posts/:post/comments/:comment', [PostsController, 'show'])
// Controller
import { bind } from '@adonisjs/route-model-binding'

import Post from '#models/post'
import Comment from '#models/comment'

export default class PostsController {
  @bind()
  async show({}, post: Post, comment: Comment) {
    return { post, comment }
  }
}

▶️ : Are you a visual learner? Checkout these screencasts to learn about Route model binding, its setup and usage.

Setup

Install the package from the npm registry as follows.

npm i @adonisjs/route-model-binding

# yarn lovers
yarn add @adonisjs/route-model-binding

Next, configure the package by running the following ace command.

node ace configure @adonisjs/route-model-binding

The final step is to register the RmbMiddleware inside the start/kernel.ts file.

import router from '@adonisjs/core/services/router'

router.use([
  // ...other middleware
  () => import('@adonisjs/route-model-binding/rmb_middleware'),
])

Basic usage

Start with the most basic example and then tune up the complexity level to serve different use cases.

In the following example, we will bind the Post model with the first parameter in the posts/:id route.

import router from '@adonisjs/core/services/router'

const PostsController = () => import('#controllers/posts_controller.js')

router.get('/posts/:id', [PostsController, 'show'])
import { bind } from '@adonisjs/route-model-binding'

import Post from '#models/post'

export default class PostsController {
  @bind()
  async show({}, post: Post) {
    return { post }
  }
}

The params and models are matched in the order they are defined. So the first param in the URL matches the first type-hinted model in the controller method.

The match is not performed using the name of the controller method argument because TypeScript decorators cannot read them (so the technical limitation leaves us with the order-based matching only).

Changing the lookup key

By default, the model's primary key is used to find a matching row in the database. You can either change that globally or change it for just one specific route.

Change lookup key globally via model

After the following change, the post will be queried using the slug property and not the primary key. In a nutshell, the Post.findByOrFail('slug', value) query is executed.

class Post extends BaseModel {
  static routeLookupKey = 'slug'
}

Change the lookup key for a single route.

In the following example, we define the lookup key directly on the route enclosed with parenthesis.

import router from '@adonisjs/core/services/router'

const PostsController = () => import('#controllers/posts_controller')

router.get('/posts/:id(slug)', [PostsController, 'show'])

Did you notice that our route now reads a bit funny?
The param is written as :id(slug), which does not translate well. Therefore, with Route model binding, we recommend using the model name as the route param because we are not dealing with the id anymore. We are fetching model instances from the database.

Following is the better way to write the same route.

import router from '@adonisjs/core/services/router'

const PostsController = () => import('#controllers/posts_controller')

router.get('/posts/:post(slug)', [PostsController, 'show'])

Change lookup logic

You can change the lookup logic by defining a static findForRequest method on the model itself. The method receives the following parameters.

  • ctx - The HTTP context for the current request
  • param - The parsed parameter. The parameter has the following properties.
    • param.name - The normalized name of the parameter.
    • param.param - The original name of the parameter defined on the route.
    • param.scoped - If true, the parameter must be scoped to its parent model.
    • param.lookupKey - The lookup key defined on the route or the model.
    • param.parent - The name of the parent param.
  • value - The value of the param during the current request.

In the following example, we query only published posts. Also, make sure that this method either returns an instance of the model or raises an exception.

class Post extends BaseModel {
  static findForRequest(ctx, param, value) {
    const lookupKey = param.lookupKey === '$primaryKey' ? 'id' : param.lookupKey

    return this
      .query()
      .where(lookupKey, value)
      .whereNotNull('publishedAt')
      .firstOrFail()
  }
}

Scoped params

When working with nested route resources, you might want to scope the second param as a relationship with the first param.

A great example of this is finding a post comment by id and making sure that it is a child of the post mentioned within the same URL.

The posts/1/comments/2 should return 404 if the post id of the comment is not 1.

You can define scoped params using the > greater than a sign or famously known as the breadcrumb sign

import router from '@adonisjs/core/services/router'

const PostsController = () => import('#controllers/posts_controller')

router.get('/posts/:post/comments/:>comment', [PostsController, 'show'])
import { bind } from '@adonisjs/route-model-binding'

import Post from '#models/post'
import Comment from '#models/comment'

export default class PostsController {
  @bind()
  async show({}, post: Post, comment: Comment) {
    return { post, comment }
  }
}

For the above example to work, you will have to define the comments as a relationship on the Post model. The type of the relationship does not matter.

class Post extends BaseModel {
  @hasMany(() => Comment)
  declare comments: HasMany<typeof Comment>
}

The name of the relationship is looked up, converting the param name to camelCase. We will use both plural and singular forms to find the relationship.

Customizing relationship lookup

By default, the relationship is fetched using the lookup key of the bound child model. Effectively the following query is executed.

await parent
  .related('relationship')
  .query()
  .where(lookupKey, value)
  .firstOrFail()

However, you can customize the lookup by defining the findRelatedForRequest method on the model (note, this is not a static method).

class Post extends BaseModel {
  findRelatedForRequest(ctx, param, value) {
    /**
     * Have to do this weird dance because of
     * https://github.com/microsoft/TypeScript/issues/37778
     */
    const self = this as unknown as Post
    const lookupKey = param.lookupKey === '$primaryKey' ? 'id' : param.lookupKey

    if (param.name === 'comment') {
      return self
      .related('comments')
      .query()
      .where(lookupKey, value)
      .firstOrFail()
    }
  }
}

Unbound params

You will often have parameters that are raw values and cannot be tied to a model. In the following example, the version is a regular string value and not backed using the database.

import router from '@adonisjs/core/services/router'

const PostsController = () => import('#controllers/posts_controller')

router.get(
  '/api/:version/posts/:post',
  [PostsController, 'show']
)

You can represent the version as a string on the controller method, and we will perform no database lookup. For example:

import { bind } from '@adonisjs/route-model-binding'

import Post from '#models/post'

class PostsController {
  @bind()
  async show({}, version: string, post: Post) {}
}

Since the route params and the controller method arguments are matched in the same order they are defined, you will always have to type-hint all the parameters.

Code of Conduct

In order to ensure that the AdonisJS community is welcoming to all, please review and abide by the Code of Conduct.

License

AdonisJS route model binding is open-sourced software licensed under the MIT license.

版本与发布记录

@adonisjs/route-model-binding 共发布 8 个版本,首次发布于 2022/05/29;过去 12 个月发布了 0 个版本。

版本发布日期距今
2.0.0-0latest2024/05/102 年前
1.0.12022/06/134 年前
1.0.0pre-prelease2022/06/134 年前
0.0.1-42022/05/304 年前
0.0.1-32022/05/304 年前
0.0.1-22022/05/304 年前

关于 @adonisjs/route-model-binding 的常见问题

@adonisjs/route-model-binding 是什么?

Route model binding for AdonisJS

如何安装 @adonisjs/route-model-binding?

在项目目录运行 npm install @adonisjs/route-model-binding,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@adonisjs/core(^6.9.0)、@adonisjs/lucid(^20.5.1)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@adonisjs/route-model-binding 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@adonisjs/route-model-binding 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@adonisjs/route-model-binding 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20.11.1。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@adonisjs/route-model-binding 可以商用吗?

@adonisjs/route-model-binding 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@adonisjs/route-model-binding 的下载量有多少?

根据 npm 官方下载统计,@adonisjs/route-model-binding 在 2026/10/05 – 2026/11/03 这 30 天内被下载 4,842 次,日均约 161 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@adonisjs/route-model-binding 还在维护吗?

最新版本 2.0.0-0 发布于 2024/05/10(2 年前);至今共发布 8 个版本,其中过去 12 个月发布了 0 个;首次发布于 2022/05/29。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。