Skip to content

Dependency injection brakes if serialize is used to wrap a transformer #3

@JanStevens

Description

@JanStevens

Package version

2.3.1

Describe the bug

Hi,

When using serialize to return the transformed resource, dependency injection fails. For example when using

import User from '#models/user'
import UserTransformer from '#transformers/user_transformer'
import type { HttpContext } from '@adonisjs/core/http'

export default class UsersController {
  async index({ serialize }: HttpContext) {
    const users = await User.query().paginate(1, 10)
    return serialize(UserTransformer.paginate(users.all(), users.getMeta()))
  }
}

with a UserTransformer which does a DI

import { inject } from '@adonisjs/core'
import { HttpContext } from '@adonisjs/core/http'
import type User from '#models/user'
import { BaseTransformer } from '@adonisjs/core/transformers'

@inject()
class GetAppUrls {
  constructor(protected ctx: HttpContext) {}
  handle() {
    return {
      url: this.ctx.request.url(),
    }
  }
}

export default class UserTransformer extends BaseTransformer<User> {
  @inject()
  toObject(getAppUrls: GetAppUrls) {
    return {
      ...this.pick(this.resource, [
        'id',
        'fullName',
        'email',
        'createdAt',
        'updatedAt',
        'initials',
      ]),
      url: getAppUrls.handle(),
    }
  }
}

The test then fails with

err: {
      "type": "RuntimeException",
      "message": "Cannot inject \"[class HttpContext]\" in \"[class EventTransformer]\"",
      "stack":
          Error
              at inject (file:///Users/project/node_modules/@adonisjs/fold/build/index.js:410:59)
              at <anonymous> (/Users/project/app/transformers/event_transformer.ts:134:1)
              at process.processTicksAndRejections (node:internal/process/task_queues:103:5)
      "name": "RuntimeException",
      "status": 500,
      "code": "E_RUNTIME_EXCEPTION",
      "help": "Container is not able to resolve \"EventTransformer\" class dependencies. Did you forget to use @inject() decorator?"
    }

I've added a repo with the reproduction steps to clearly pinpoint the issue. If you need any more info let me know.

Regards

Reproduction repo

https://github.com/JanStevens/adonisv7-serialize-inject-issue

Metadata

Metadata

Assignees

Labels

Type: BugThe issue has indentified a bug

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions