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

@vmagination/request-typegen

v0.3.2

Published

Dynamic type generator for API responses

Downloads

111

Readme

Request TypeGen

Dynamic type generator for API responses.

preview

Current version is more of a proof of concept. It works, and it may be used in production since it's only designed for use during development. But it's not yet optimized, and you might need to do some extra steps to make it work in some environments.

Making requests to API is a common task in any application. But adding types can be a tedious task, especially if API is in active development and changes return fields. This library aims to make it easier by generating and updating types for you. The only question you have to ask yourself is: Are you lazy enough to install a library to not do something trivial manually?

Installation

To install type gen simple run:

npm install --save @vmagination/request-typegen
yarn add @vmagination/request-typegen

Add global types file to typescript config (tsconfig.json). It will not exist until you generate types for the first time.

{
  ...
  "include": [..., "typeGen.d.ts"]
}

Notes for specific environments

Use different import paths

// "moduleResolution": "NodeNext",
import { typeGenWrapper } from '@vmagination/request-typegen/node';
// "moduleResolution": "Node", or others
import { typeGenWrapper } from '@vmagination/request-typegen/for/node';

Add dev dependency vite-plugin-fs

And use different import paths

// "moduleResolution": "NodeNext",
import { typeGenWrapper } from '@vmagination/request-typegen/vite';
// "moduleResolution": "Node", or others
import { typeGenWrapper } from '@vmagination/request-typegen/for/vite';

Starting file server is required to generated types

  npx typegen-file-server start --port 4832

or open in new terminal

  start "typegen server" npx typegen-file-server start --port 1234

Default port is 4832

Use different import paths and add file server url to config

// "moduleResolution": "NodeNext",
import { typeGenWrapper } from '@vmagination/request-typegen/react-native';
// "moduleResolution": "Node", or others
import { typeGenWrapper } from '@vmagination/request-typegen/for/react-native';

const request = typeGenWrapper(fetch, {
  enabled: __DEV__,
  fsUrl: 'http://${externalIP}:${port}',
});

Starting file server is required to generated types

  npx typegen-file-server start

or open in new terminal

  start "typegen server" npx typegen-file-server start --port 1234

Default port is 4832

Add file server url to config

import { typeGenWrapper } from '@vmagination/request-typegen';

const request = typeGenWrapper(fetch, {
  enabled: __DEV__,
  fsUrl: 'http://localhost:4832',
});

API reference

typeGenWrapper

typeGenWrapper(requestFn, config)

A brief description of what the function does and its purpose in the library.

Parameters

  • requestFn (Function): Can be literally any function that accepts any parameters and returns any value. Will be wrapped and extended.
  • config (TypeGenConfig): Configuration for type generation.
type TypeGenConfig<T extends Fn, RT extends Promise<any>> = {
  enabled?: boolean; // should enable type generation, pass isDev flag here
  ignoreConstructors?: boolean; // should generate types for non-default objects
  writeFile: (path: string, content: string) => any | Promise<any>;
  // ^ overrides default writeFile function for saving type file
  readFile: (path: string) => any | Promise<any>;
  // ^ overrides default readFile function for reading saved type file
  fileExists: (path: string) => any | Promise<any>;
  // ^ overrides default fileExists function for checking saved type file
  focusField?: string; 
  // ^ focus on specific return field for type generation, the field can be a function
  // ^ must be provided if the field is not json (fetch) or data (axios)
}

Return Value

Returns wrapped original function with extended functionality. All added methods do the same thing, but with different call formats.

All methods require the addition of a type generation key (string). It is recommended to use the endpoint's static name as a key.

type TypeGenWrapperResult<T extends Fn> = T & {
  withTypeGen: <K extends string>(key: K) => {
    call: (...args: Parameters) => any | GeneratedType
  };
  callWithTypeGenKey: TGVariant1<Parameters<T>>;
  tg: <K extends string>(key: K) => {
    call: (...args: Parameters) => any | GeneratedType
  };
  tgS: <K extends string>(key: K, ...args: Parameters) => any | GeneratedType;
  tgE: <K extends string>(...args: [...Parameters, K]) => any | GeneratedType;
};

Example

// Simple default fetch wrapper

const request = typeGenWrapper(fetch);

const result = await request.withTypeGen('getUsers').call('https://myapi.com/users');
const result = await request.tg('getUsers').call('https://myapi.com/users');
const result = await request.tgS('getUsers', 'https://myapi.com/users');
const result = await request.callWithTypeGenKey('getUsers', 'https://myapi.com/users');
const result = await request.tgE('https://myapi.com/users', 'getUsers');
// Axios wrapper

const request = typeGenWrapper(axois, {
  getReadableResponse: (res) => res.data,
});

const result = await request
  .tg('postUsers')
  .call('https://myapi.com/users', { method: 'POST' });
const result = await request
  .withTypeGen('postUsers')
  .call('https://myapi.com/users', { method: 'POST' });
const result = await request
  .tgS('postUsers', 'https://myapi.com/users', { method: 'POST' });
const result = await request
  .callWithTypeGenKey('postUsers', 'https://myapi.com/users', { method: 'POST' });
const result = await request
  .tgE('https://myapi.com/users', { method: 'POST' }, 'postUsers');

ToDo list

  • [ ] Find a way to derive stable key from function arguments
  • [ ] Find a way to avoid using file server or a way to start it automatically
  • [ ] Find a reason to continue development