vendure-ecommerce / vendure

The commerce platform with customization in its DNA.
https://www.vendure.io
Other
5.81k stars 1.04k forks source link

Document RequestContext creation more explicitly #3132

Open DanielBiegler opened 1 month ago

DanielBiegler commented 1 month ago

Is your feature request related to a problem? Please describe.

I only found out how to actually construct the correct context for my use case (plugin lifecycle hook) by reading Vendures source instead of the docs. For example the section about standalone scripts just mentions:

    const ctx = await app.get(RequestContextService).create({
        apiType: 'admin',
    });

but doesnt mention the user option which made the context fail for me in services like the RoleService.

Found a small snippet in the repo and slightly modified it, which works nicely now:

    const { superadminCredentials } = this.configService.authOptions;
    const superAdminUser = await this.connection
      .getRepository(RequestContext.empty(), User)
      .findOneOrFail({
        where: {
          identifier: superadminCredentials.identifier,
        },
      });

    const ctx = await this.requestContextService.create({
      apiType: "admin",
      user: superAdminUser,
    });

Describe the solution you'd like

Small example:

import { OnApplicationBootstrap } from "@nestjs/common";
import { VendurePlugin, ProcessContext } from "@vendure/core";

@VendurePlugin({
    // ...
})
export class MyPlugin implements OnApplicationBootstrap {
  constructor(private processContext: ProcessContext) {}

  async onApplicationBootstrap() {
    if (this.processContext.isWorker) return;

    // Do something on the server
  }

  // ...
}

Describe alternatives you've considered

--

Additional context

--

michaelbromley commented 1 month ago

Thanks - all good suggestions. Are you interested in submitting a PR for these changes?

DanielBiegler commented 1 month ago

I was hoping someone else could do it.