nestjs-keycloak-admin icon indicating copy to clipboard operation
nestjs-keycloak-admin copied to clipboard

ESM restriction - what to do?

Open glappsi opened this issue 2 years ago • 4 comments

You stated

Due to @keycloak/keycloak-admin-client package, nestjs-keycloak-admin can't support CommonJS at the moment. The team behind keycloak-admin-client made the decision to have a breaking change and support CommonJS. Please refer to this Github issue for more information about their decision-making process.

What do I need to change in my nestjs configuration for it to work?

glappsi avatar May 18 '23 09:05 glappsi

Hey @glappsi Had the same problem

We ended up making our own fork and using commonjs support there.

Nestjs is not easily get updated to esm.

revolist avatar May 19 '23 09:05 revolist

Following provided solutions in the original Github issue thread, your best shot when you want to use keycloak-admin-client is to use a custom package that forks and rebuilds it, to be able to use it

If you don't want to do it yourself, you can use someone else's fork, like this one : Github or NPM

So if I understand everything correctly, you would have to do the same for nestjs-keycloak-admin? 🤔

TBG-FR avatar May 22 '23 10:05 TBG-FR

I've recompiled:

https://www.npmjs.com/package/@cybercoder/keycloak-admin-client

cybercoder avatar Jul 30 '23 07:07 cybercoder

you can also dynamically import it, I have done it with nest and typescript

type ImportClass<T, K extends keyof T> = T extends Record<K, infer S>
  ? S extends new (...args: any[]) => infer R
    ? R
    : never
  : never;
export type KeycloakAdminClient = ImportClass<
  typeof import('@keycloak/keycloak-admin-client'),
  'default'
>;

export async function loadKeycloakAdminClient() {
  try {
    return (await eval("import('@keycloak/keycloak-admin-client')"))
      .default as typeof import('@keycloak/keycloak-admin-client').default;
  } catch (error) {
    return (await import('@keycloak/keycloak-admin-client')).default;
  }
}

then in onmoduleinit you can await the promise and instantiate a kcadmin client object. I will note that for some reason jest tests do not work (even if run with esm enabled) but tests do work with vitest, it manipulates import statements so we need the catch in the function it won't work with just the eval

satanshiro avatar Aug 24 '23 09:08 satanshiro