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

ab-initio

v1.2.1

Published

A simple way to keep in sync Next api definitions and client types using zod

Downloads

1,064

Readme

Initio

Initio is an project designed to streamline the development of new applications and their accompanying documentation. Based on Typescript, Next.js, Zod, ReqctQuery, and the zod-to-openapi library—NextBase significantly reduces the overhead typically associated with these processes.

Getting started

Prerequisites

  • pnpm v8.6.11
  • node v18.17.0
  • vscode

Core Concepts

Schema

At the heart of Initio is the Schema, a ZodObject that defines the structure for key elements of an API request, including query parameters, URL parameters, rquest body, and response. This robust schema validation ensures consistency and reliability across your application. The schemas will be located on each app acording to the domain of each app. This way every app can set their own scope foe each schema. An example of this schema could be app/data/geo/schemas.ts containing:

/* eslint-disable @typescript-eslint/no-unused-vars */
/* eslint-disable @typescript-eslint/no-namespace */
import { extendZodWithOpenApi } from '@asteasolutions/zod-to-openapi';
import { z } from 'zod';

extendZodWithOpenApi(z);
export namespace GeoDefinitions {
  export namespace Schemas {
    export const Coordinates = z
      .object({
        latitude: z.number(),
        longitude: z.number(),
      })
      .openapi('Coordinates');

    export const LocationData = z
      .object({
        city: z.string(),
        state: z.string(),
        country: z.string(),
      })
      .openapi('LocationData');
  }

  export namespace Types {
    export type Coordinates = z.infer<typeof Schemas.Coordinates>;
    export type LocationData = z.infer<typeof Schemas.LocationData>;
  }
}

Request Handler

Initio proposes a request/api driven development, this means that all the api endpoins are defined first setting the input, output, params and query formats so when handler function is defined it has access to auto complete features and the same happens with consumer. An example of a request definition can be as follow:

import { createAPIDefinition } from 'ab-initio/dist/ab-initio';
import { GeoDefinitions } from './schemas';

export const getGeoData = createAPIDefinition({
  endpoint: '/geo',
  schemas: {
    queryParams: GeoDefinitions.Schemas.Coordinates,
    response: GeoDefinitions.Schemas.LocationData,
  },
});

export const postGeoData = createAPIDefinition({
  method: 'post',
  endpoint: '/geo',
  schemas: {
    payload: GeoDefinitions.Schemas.Coordinates,
    response: GeoDefinitions.Schemas.LocationData,
  },
});

And the used in the next api definition as follows:

import { apiWrapper } from 'ab-initio/dist/server';
import { getGeoData, postGeoData } from '../../../data/geo/api';

export const GET = apiWrapper(getGeoData, async (request) => {
  const searchParams = request.nextUrl.searchParams;
  const lat = searchParams.get('latitude');
  const long = searchParams.get('longitude');
  const locationResponse = await fetch(
    `https://geocode.xyz/${lat},${long}?json=1`,
  );
  const locationData = await locationResponse.json();
  return locationData.standard || locationData;
});

export const POST = apiWrapper(
  postGeoData,
  async (_request, _queryParams, payload) => {
    const lat = payload?.latitude;
    const long = payload?.longitude;
    const locationResponse = await fetch(
      `https://geocode.xyz/${lat},${long}?json=1`,
    );
    const locationData = await locationResponse.json();
    const fullData = locationData.standard || locationData;
    return {
      city: fullData.city,
      state: fullData.state,
      country: fullData.country,
    };
  },
);

Consumer

Initio consumers are objects based in a request definition that uses react query internally to perform the comunication to the api. Even if api is not implemented in the next app, the definition of it will be helpful to use it on the auto generation of documentation and also the consumers. Here is an example to a consumer using the previous definition:

'use client';
import { ChangeEvent, useCallback, useEffect, useState } from 'react';
import { apiConsumerClient } from 'ab-initio/dist/client';
import { Input } from '@next-base/lib-ui';
import { postGeoData } from 'apps/next-base/data/geo/api';

const geoDataConsumer = apiConsumerClient(postGeoData);

const GeoData = function Index() {
  const [latitude, setLatitude] = useState(19.3906594);
  const [longitude, setLongitude] = useState(-99.308425);
  const { query, queryKey } = geoDataConsumer(
    {
      body: {
        latitude,
        longitude,
      },
    },
    {},
  );

  const onChangeLatitude = (ev: ChangeEvent<HTMLInputElement>) => {
    setLatitude(Number(ev.target.value));
  };

  const onChangeLongitude = (ev: ChangeEvent<HTMLInputElement>) => {
    setLongitude(Number(ev.target.value));
  };

  if (query.isLoading) return <>Loading...</>;

  if (query.error) return <>Error</>;

  return (
    <>
      <Input
        placeholder="latitude"
        onChange={onChangeLatitude}
        value={latitude}
      />
      <Input
        placeholder="longitude"
        onChange={onChangeLongitude}
        value={longitude}
      />
      <br />
      <textarea style={{ width: '100%', height: '40px' }}>
        {JSON.stringify(query.data)}
      </textarea>
      <br />
      <textarea style={{ width: '100%', height: '40px' }}>
        {JSON.stringify(queryKey)}
      </textarea>
      <br />
    </>
  );
};

export default GeoData;

Donate

paypal