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

redoc-builder

v1.1.11

Published

A powerful tool for building OpenAPI documentation. This will allow you to build a single page documentation for your API. All endpoints or paths can be added to the documentation by using the builders provided by this package.

Downloads

68

Readme

.github/workflows/publish.yml

Redoc Builder

A powerful tool for building OpenAPI documentation. This will allow you to build a single page documentation for your API. All endpoints or paths can be added to the documentation by using the builders provided by this package. This tool does NOT support CommonJS

Table of contents

Installation

actually only tested in bun

npm install --save redoc-builder
bun i redoc-builder
pnpm add redoc-builder
yarn add redoc-builder

Example

// index.ts

import { ParameterIn, PathOperationType, RedocBuilder, SchemaPropertyFormatType, SchemaSecurityBuilder, SchemaSecurityStyle, SchemaType } from "redoc-builder";

const specification = new RedocBuilder()
.setVersion('3.1.0')
.setInfo((info) => 
    info.setTitle("Skyraid MC Discord bot Rest API")
    .setDescription("This is an example of how the builders could work inside your code work.")
    .setContact((contact) =>
        contact.setName('Support Team')
        .setUrl('https://mintymedia.nl/contact')
        .setEmail('[email protected]')
    )
    .setLogo((logo) => 
        logo.setUrl('https://dev.mintycloud.nl/images/logo.png')
        .setBackgroundColor('#FFFFFF')
        .setAltText('Winstore Image API')
    )
    .setLicense((license) => 
        license.setName('MIT')
        .setUrl('https://opensource.org/licenses/MIT')
    )
)
// .setSchemas(await parseSchemas())
.setSchemas([new SchemaSecurityBuilder()
    .setKeyName('Basic')
    .setName('Authorization')
    .setStyle(SchemaSecurityStyle.ApiKey)
    .setDescription('Use the API key that has been set in the .env file')
    .setLocation(ParameterIn.Header)
    // .setTag('tag/Authentication')
])
.addPath((path) => 
    path.setPath('/mc/link/{playerUUID}')
    .setOperations((operation) => 
        operation.addTag('Minecraft')
        .setType(PathOperationType.GET)
        .setSummary("Get a linked user by it's minecraft uuid")
        .setDescription('Get data from a minecraft uuid.')
        .setOperationId('get-link-player')
        .setParameters((parameter) => 
            parameter.setName('playerUUID')
            .setLocation(ParameterIn.Path)
            .setRequired()
            .setDescription("The minecraft player uuid\n#### Validation Errors\n- uuid must be exact 32 characters long\n\n- uuid must be a valid uuid\n- uuid without dashes `-`")
            .setSchema(SchemaType.String, (builder) => 
                builder.setExample('ad468e72946f4238b86bc774a6e49d16')
                .setMaxLength(32)
                .setMinLength(32)
                .setFormat(SchemaPropertyFormatType.Uuid)
                .setEnum(['ad468e72946f4238b86bc774a6e49d16'])
            )
        )
        .setResponses((response) => 
            response.setCode(200)
            .setDescription('API Success Response')
            // .setSchema(SchemaType.Object, new SchemaObjectBuilder(util.parseSchema(linked_userSchema, 'Testing')))
            .setSchema(SchemaType.ItemReference, (builder) => builder.setRef('#/components/schemas/LinkedUser'))
            .setMediaType('application/json')
        )
    )
)
.setTags((tag) => tag.setName('Minecraft').setDisplay('Minecraft Endpoints').setDescription('Testing!'))
.setTagGroups({name: 'API', tags: ['Minecraft']})

Using zod schemas

The following code requires a few things:

  • Must have a folder called schemas with files that export the schema.
  • Only schema objects will be parsed.

Example schema:

import { z } from "zod"
export const private_channelSchema = z.object({
    owner_id: z.string(),
    channel_id: z.string(),
    channel_updated_at: z.coerce.date().default(new Date())
});

export type PrivateChannel = z.infer<typeof private_channelSchema>;

Zod Schema Parsing

Only a specific amount of zod types are being used:

  • ZodString
  • ZodNumber
  • ZodDate
  • ZodArray
  • ZodEffects
  • ZodEnum

A set of zod kinds are used (or ignored):

  • Length
  • Min
  • Max
  • Email
  • Uuid
  • Url
  • Regex
  • Trim
  • Includes
  • ToLowerCase
  • ToUpperCase
  • StartsWith
  • EndsWith
  • Datetime
  • Ip
  • Int

This schema would be added in the openapi specification as:

{ 
    "PrivateChannel": {
        "type": "object",
        "required": [
            "owner_id",
            "channel_id"
        ],
        "properties": {
            "owner_id": {
                "type": "string"
            },
            "channel_id": {
                "type": "string"
            },
            "channel_updated_at": {
                "type": "string",
                "format": "date-time"
            }
        }
    }
}

Examples

Example made in Bun


import { dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import { readdirSync } from "node:fs";
import { RedocBuilder, RedocUtils } from 'redoc-builder';


/**
 * @param str - The schema name
 */
const capitalizeFirstLetter = (str: string) => str.replace(/^[a-zA-Z]|_[a-zA-Z]?/g, (match) => match.replace("_", "").toUpperCase())

const parseSchemas = async () => {

    const util = new RedocUtils();

    const schemas: SchemaObject[] = [];

    const root = dirname(fileURLToPath(import.meta.url));

    /** Resolving schema paths from "schemas" folder */
    const files = readdirSync(`${root}/../schemas`).filter(
        (f) => f.endsWith('.ts') || f.endsWith('.js')
    );

    for(const file of files) {

        const schema = await import(`../schemas/${file}`);
        const keys = Object.keys(schema);

        const name = capitalizeFirstLetter(keys[0]).replace('Schema', '');
        schemas.push(util.parseSchema(schema[keys[0]] as ZodObject<any>, name))
    }

    return schemas;
}

// Now use this function for the specification

const specification = new RedocBuilder()
.setSchemas(await parseSchemas()) // done

Have fun :)