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

api-mapping-router

v2.0.1

Published

This library has the objective of executing functions sending parameters and obtaining the result, through a tunnel that transfers text.

Downloads

3

Readme

API Mapping Router

This library has the objective of executing functions sending parameters and obtaining the result, through a tunnel that transfers text.

Useful examples where to use:

  • NextJs to execute backend functions from the client
  • Monorepo where you can import files from back to the front.

How to Implement?

Backend

create context.ts file with context type

export interface Context {
	req: NextApiRequest
}

create a resolver function in any file

import { CreateResolver } from "api-mapping-router/resolver";

// Define the resolver types
interface AuthUpdateProfileParams extends JSONObject {
	firstName?: string;
	lastName?: string;
}

interface AuthUpdateProfileResult extends JSONObject {
	firstName: string;
	lastName: string;
}

// Create a resolver
export const AuthUpdateProfileResolver = CreateResolver<
	AuthUpdateProfileParams,
	AuthUpdateProfileResult,
	Context
>({
	// Validations params or undefined
	params: {
		parse: (v) => {
			if (typeof v !== 'object' || v === null) {
				throw new Error('invalid param type');
			}
			if ('firstName' in v && typeof v['firstName'] !== 'string') {
				throw new Error('invalid property firstName');
			}
			if ('lastName' in v && typeof v['lastName'] !== 'string') {
				throw new Error('invalid property lastName');
			}
			return v as AuthUpdateProfileParams;
		}
	},
	// Middlewares or undefined
	middlewares: [
		async (props) => {
			if (!props.ctx.req.headers.autenticated) {
				throw new Error('unauthorized');
			}
		}
	],
	// Feature method
	method: async (props) => {
		const claims = JSON.parse(props.ctx.auth.token || '');
		return { ...claims, ...props.params };
	}
});

create map.ts file where the function map is created executables.

import { CreateMap } from "api-mapping-router/map";

import { AuthUpdateProfileResolver } from './resolver.ts';

export const map = CreateMap({
    auth: {
        profile: {
			update: AuthUpdateProfileResolver
		},
        signIn: async (params: AuthSignInParams): Promise<User> => {
            ...
        }, 
        signUp: async (params: AuthSignUpParams): Promise<User> => {
            ...
        },
        ...
    },
    user: {
        profile: {
            get: async (): Promise<User> => {
                ...
            },
            ...
        },
        ...
    }
});

export type Map = typeof map;

already with the function map created for example in NextJs you have to create the file for example: /pages/api/index.ts to run the functions over HTTP.

import { NextApiHandler } from "next";
import { CreateServer } from "api-mapping-router/server";

import { map } from 'src/server/map';

const server = CreateServer(map);

const handler: NextApiHandler = async (req, res) => {
    if (req.method !== "POST") {
        return res.status(404).end();
    }

    try {
        const result = await server.tunnel.execute(data, { req });
        res.status(200).send(result);
    } catch (e) {
        res.status(400).send(JSON.stringify({
            error: e instanceof Error ? e.message : 'unknow error'
        }));
    }
};

export default handler;

Frontend

on the client the file is created in the services folder index.ts which calls the server api.

import { CreateClient } from "api-mapping-router/client";

import type { Map } from 'src/server/map';

export const client = CreateClient<typeof appMap>({
    tunnel: async (data: string) => {
        const response = await fetch('/api', {
            headers: {
                'Content-Type': 'text/plain',
                'Autenticated': `Basic ${window.localStorage.get('token')}`
            },
            method: 'POST',
            body: data
        });

        return await response.text();
    }
});

functions can now be called from the front using the client. The great advantage of this is that it is completely typed the map object on the client.

import { client } from 'src/services';

client.methods.auth.signIn.exec(...params)
    .then((result) => {
        ...
    })
    .catch((error) => {
        ...
    })