0.4.0 • Published 10 months ago

@http-rpc/server v0.4.0

Weekly downloads
-
License
MIT
Repository
github
Last release
10 months ago

HTTP RPC Server

Documentation

Full documentation can be found here.

Installation

npm i @http-rpc/server zod fastify superjson

Usage

./app.ts

import { fastifyRPCPlugin } from '@http-rpc/server/adapters/fastify';
import superjson from 'superjson';
import { router } from './rpc/router';

fastify.register(fastifyRPCPlugin, {
	prefix: '/rpc',
	router,
	transformer: superjson,
});

./router.ts

import { createRoute, RPCError } from '@http-rpc/server';
import { FastifyContext } from '@http-rpc/server/adapters/fastify';
import { z } from 'zod';

const publicRoute = createRoute<FastifyContext>();
const authenticatedRoute = publicRoute.middleware(ctx => {
	const { authorization } = ctx.req.headers;
	const user = await prisma.user.findUnique({
		where: { token: authorization },
	});
	if (!user) throw new RPCError({ code: 'UNAUTHORIZED' });

	return {
		userId: user.id,
	};
});

export const router = {
	version: publicRoute
		.output(
			z.object({
				version: z.string(),
			}),
		)
		.get(() => ({ version: '1.0.0' })),
	orders: {
		list: authenticatedRoute
			.input(z.object({ fields: z.array(z.string()) }))
			.output(z.array(z.object({ id: z.number(), amount: z.number() })))
			.get(ctx => {
				const { userId } = ctx;
				const { fields } = ctx.input;
				return await prisma.order.findMany({
					where: {
						userId,
					},
					select: Object.keys(fields).reduce((acc, field) => {
						acc[field] = true;
						return acc;
					}, {}),
				});
			}),
	},
};

export type Router = typeof router;
0.2.16

1 year ago

0.2.15

1 year ago

0.3.0

1 year ago

0.4.0

10 months ago

0.2.14

1 year ago

0.2.13

1 year ago

0.2.12

1 year ago

0.2.11

1 year ago

0.2.10

1 year ago

0.2.1

1 year ago

0.2.0

1 year ago

0.2.7

1 year ago

0.2.6

1 year ago

0.2.9

1 year ago

0.2.8

1 year ago

0.2.3

1 year ago

0.2.2

1 year ago

0.2.5

1 year ago

0.2.4

1 year ago

0.1.3

1 year ago

0.1.0

1 year ago

0.1.2

1 year ago

0.1.1

1 year ago

0.0.15

1 year ago

0.0.16

1 year ago

0.0.11

1 year ago

0.0.12

1 year ago

0.0.13

1 year ago

0.0.14

1 year ago

0.0.10

1 year ago

0.0.9

1 year ago

0.0.8

1 year ago

0.0.4

1 year ago

0.0.3

1 year ago

0.0.2

1 year ago

0.0.1

1 year ago