anonrig / nestjs-keycloak-admin

Keycloak client and admin provider for Nest.js applications with built-in User Managed Access (UMA) and ACL support.
https://npmjs.com/package/nestjs-keycloak-admin
MIT License
181 stars 25 forks source link

ESM restriction - what to do? #173

Open glappsi opened 1 year ago

glappsi commented 1 year ago

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?

revolist commented 1 year ago

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.

TBG-FR commented 1 year ago

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? 🤔

cybercoder commented 1 year ago

I've recompiled:

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

satanshiro commented 1 year ago

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