npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@leancodepl/api-proxy

v0.5.0

Published

LeanCode contacts generator nest api proxy with auth token forwarder

Downloads

7

Readme

api-proxy

Used for authentication and communication with a contractsgenerator based api.

Usage

register

import { VerifyOptions } from "jsonwebtoken";

ApiProxy.register({ isGlobal, jwtStrategyConfig }: ApiProxySyncConfiguration): DynamicModule

export type ApiProxySyncConfiguration = {
    isGlobal?: boolean;
    jwtStrategyConfig: JwtStrategyConfig;
};

export type JwtStrategyConfig = {
    jwksUri: string;
    jsonWebTokenOptions?: VerifyOptions;
};
isGlobal

You can specify if you want to register a module globally.

jwksUri

Uri of your auth jwks.

jsonWebTokenOptions

VerifyOptions is a type imported from jsonwebtoken package.

export interface VerifyOptions {
    algorithms?: Algorithm[] | undefined;
    audience?: string | RegExp | Array<string | RegExp> | undefined;
    clockTimestamp?: number | undefined;
    clockTolerance?: number | undefined;
    /** return an object with the decoded `{ payload, header, signature }` instead of only the usual content of the payload. */
    complete?: boolean | undefined;
    issuer?: string | string[] | undefined;
    ignoreExpiration?: boolean | undefined;
    ignoreNotBefore?: boolean | undefined;
    jwtid?: string | undefined;
    /**
     * If you want to check `nonce` claim, provide a string value here.
     * It is used on Open ID for the ID Tokens. ([Open ID implementation notes](https://openid.net/specs/openid-connect-core-1_0.html#NonceNotes))
     */
    nonce?: string | undefined;
    subject?: string | undefined;
    maxAge?: string | number | undefined;
}

register example

const apiProxySyncConfig: ApiProxySyncConfiguration = {
    isGlobal: false,
    jwtStrategyConfig: {
        jwksUri: "https://localhost:3333/auth/.well-known/openid-configuration/jwks",
        jsonWebTokenOptions: {
            audience: "internal_api",
        },
    },
};

@Module({
    imports: [ApiProxyModule.register(apiProxySyncConfig), PassportModule.register({ defaultStrategy: "jwt" })],
    controllers: [],
    providers: [],
})
export class AppModule {}

registerAsync

ApiProxy.registerAsync(options: ApiProxyAsyncConfiguration): DynamicModule

export type ApiProxyConfiguration = {
    jwtStrategyConfig: JwtStrategyConfig;
};

export interface ApiProxyAsyncConfiguration extends Pick<ModuleMetadata, "imports"> {
    useExisting?: Type<ApiProxyConfigurationFactory>;
    useClass?: Type<ApiProxyConfigurationFactory>;
    useFactory?: (...args: any[]) => Promise<ApiProxyConfiguration> | ApiProxyConfiguration;
    inject?: any[];
    extraProviders?: Provider[];
    isGlobal?: boolean;
}

export interface ApiProxyConfigurationFactory {
    createApiProxyConfiguration(): Promise<ApiProxyConfiguration> | ApiProxyConfiguration;
}

Every property will work the same as in the nestjs documentation. If none of useExisting, useClass and useFactory is specified, method will throw a NotFoundException.

registerAsync example

const apiProxyAsyncConfig: ApiProxyAsyncConfiguration = {
    isGlobal: false,
    imports: [ConfigModule],
    useFactory: (configService: ConfigService) => ({
        jwtStrategyConfig: {
            jwksUri: configService.get("JWKS_URI") ?? "",
            jsonWebTokenOptions: {
                audience: "internal_api",
            },
        },
    }),
    inject: [ConfigService],
};

@Module({
    imports: [
        ConfigModule.forRoot(),
        ApiProxyModule.registerAsync(apiProxyAsyncConfig),
        PassportModule.register({ defaultStrategy: "jwt" }),
    ],
    controllers: [],
    providers: [],
})
export class AppModule {}

UseJwtGuard decorator

For the authorization to work, you have to use the UseJwtGuard decorator on your controller.

import { UseJwtGuard } from "@leancodepl/api-proxy";

@UseJwtGuard()
@Controller()
export class AppController {
    constructor() {}
}

Providing a CqrsClient example

import Client from "./Client";

@Injectable()
export class CqrsClient1 {
    client;
    constructor(cqrsClientFactory: CqrsClientFactory) {
        this.client = Client(cqrsClientFactory.create(CqrsClient1.getApiEndpoint));
    }

    static getApiEndpoint(type: string) {
        return `http://localhost:3333/api/${type}`;
    }
}

Into your Client function, generated with contractsgenerator-typescript, you have to pass the instance of CqrsClient, which can be created using cqrsClientFactory.create method. As args of this method you have to pass a function with args (type: string), which will be used for creating endpoint's url.

@Injectable()
export class Query1ComponentService {
    constructor(private client: CqrsClient1) {}

    async getComponent() {
        const test = await this.client.client.TestQueries.TestQuery1({});
        return <SampleComponent testString={test.test} />;
    }
}

Then you will be able to use your client's queries and commands.

Remember to add those classes as providers of your module.

@Module({
    imports: [ApiProxyModule.register(apiAndAuthConfig), PassportModule.register({ defaultStrategy: "jwt" })],
    providers: [CqrsClient1, Query1ComponentService],
})
export class AppModule {}