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

@cuple/server

v1.0.7

Published

typescript-based RPC with REST compatibility

Downloads

202

Readme

@cuple/server

Server side for @cuple RPC.

Installation

npm i @cuple/server express zod

Examlpe

import express from "express";
import { z } from "zod";
import { createBuilder, initRpc } from "@cuple/server";
import { apiResponse, success } from "@cuple/server";

const app = express();
const builder = createBuilder(app); // STEP 1: Create builder with the express instance

let lastId = 2;
const posts = [
  { id: 1, title: "Hi again", content: "This is my second post" },
  { id: 2, title: "Hi", content: "This is my first post" },
];

// STEP 2: Define some request handlers
export const routes = {
  getPosts: builder.get(async () => {
    return success({ posts });
  }),
  addPost: builder
    .bodySchema(
      z.object({
        title: z.string(),
        content: z.string(),
      })
    )
    .post(async ({ data }) => {
      lastId += 1;
      const newPost = { id: lastId, ...data.body };
      posts.push(newPost);
      return success({
        message: "The post has been created successfully",
        post: newPost,
      });
    }),
};

// STEP 3: Create the RPC handler (Required to use with @cuple/client)
initRpc(app, { path: "/rpc", routes });

app.listen(8080, () => {
  console.log(`Example app listening on port 8080`);
});

API

Feature 1: Basic handlers

builder.get(({ req, res, data }) => { /*...*/ });
builder.post(({ req, res, data }) => { /*...*/ });
builder.put(({ req, res, data }) => { /*...*/ });
builder.patch(({ req, res, data }) => { /*...*/ });
builder.delete(({ req, res, data }) => { /*...*/ });

Feature 2: Schema parsers

It requires zod

Example:

// server
builder
  .headersSchema(z.object({ authorization: z.string() }))
  .get(({ data }) => {
    console.log(data.headers.authorization);
  });

Variants:

// For HTTP headers
// NOTE: It has to use the same naming as req.headers
.headersSchema(z.object({ authorization: z.string() }))

// For HTTP request body parsing
.bodySchema(z.object({
    user: z.object({
        name: z.string().min(3),
        age: z.number()
    })
}))

// For URL query parsing (e.g.: ?somevar=12)
.querySchema(z.object({ "somevar": z.coerce.number() }))

// For URL params parsing
.path("/post/:id")
    .paramsSchema(z.object({ "id": z.coerce.number() }))

Feature 3: Middlewares

NOTE: Check out Feature 4 as well.

builder
  .middleware(async () => {
    const randomValue = Math.random();
    if (randomValue > 0.5) return { next: true, randomValue };
    return { next: false, statusCode: 500, message: "Unlucky" };
  })
  .get(async ({ data }) => {
    return success({
      message: `You won visiting this page with ${data.randomValue}`,
    });
  });

Feature 4: Chaining

const authLink = builder
  .headersSchema(
    z.object({
      authorization: z.string(),
    })
  )
  .middleware(async ({ data }) => {
    if (data.headers.authorization === "foo")
      return {
        next: true,
      };
    return {
      next: false,
      statusCode: 401 as const,
    };
  })
  .buildLink();
const routes = {
  getAuthedWelcomeMessage: builder.chain(authLink).get(async () => {
    return success({
      message: "hi",
    });
  }),
};

Feature 5: Groups


const authModule = {
    login: /*...*/,
    register: /*...*/,
}

const postsModule = {
    getPost: /*...*/,
    getPosts: /*...*/,
    createPost: /*...*/,
    deletePost: /*...*/,
}

const app = {
    auth: authModule,
    posts: postsModule
}

export type Routes = typeof app;