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

@hiotlabs/hiot-api-interface

v1.2.1

Published

Api interface for Hiotlabs services

Downloads

183

Readme

hiot-api-interface

Examples:

Exports

Available exports

import { get, post, put, patch, del,  internal, JsonResponse, prepareJsonSchemas, Method } from "hiot-api-interface";

Endpoints

export default get({
   /** The path to the endpoint */
  path: string,

  /** The activity that is required to access this endpoint */
  authorized: string,

  /** Whether you need to be logged in or not to access the endpoint. Only needed if authorized is not used. */
  authenticated?: boolean;

   /**
    * The request schema, either a JSON schema or the name of a typescript type
    * (See below. The name must match the name of the file in ./api/schemas).
    **/
  requestSchema: string | object;,

  /** The request handler function */
  requestHandler: (req: Request<any>, res: Response<any>, next: Next) => Promise<JsonResponse<any> | void>,

  /** Additional route options */
  opts?: RouteOptions;

   /** The documentation for the endpoint */
  documentation: {
    /** A short summary of the endpoint */
    summary: string,

    /** A longer description of the endpoint */
    description: string,

    /** Optional array of tags */
    tags?: string[];

    /**
     * Optional description for query params (can also be defined and described in the json schema,
     * since that's how we validate them)
     **/
    query?: Record<string, string>;

    /**
     * Optional description of url parameters.
     * Usually unnecessary since url params should be self descriptive, e.g. /dashboards/:dashboardId
     **/
    parameters?: Record<string, string>;

    /** The responses that can be returned by the endpoint */
    responses: [
      {
        /** The http status code of the response */
        status: number,

        /**
         * An optional response schema, either a JSON schema or the name of a typescript type
         * (See below. The name must match the name of the file in ./api/schemas).
         **/
        schema: string,

        /** An optional description of the response */
        description?: string,
      },
    ],
  },
});

Example

import { get, JsonResponse } from "hiot-api-interface";

export const GET_DASHBOARDS_PATH = "/dashboards";
export const GET_DASHBOARDS_ACTIVITY = ["dashboards", "getDashboards"];

export default get({
  path: GET_DASHBOARDS_PATH,
  authorized: GET_DASHBOARDS_ACTIVITY,
  requestSchema: GET_DASHBOARDS_REQUEST_SCHEMA,
  requestHandler: getDashboardsEndpoint,
  documentation: {
    summary: "Get dashboards",
    description: "Gets all dashboards",
    responses: [
      {
        status: 200,
        schema: GET_DASHBOARDS_RESPONSE_SCHEMA,
      },
    ],
  },
});

async function getDashboardsEndpoint(req: Request<GetDashboardsRequestSchema>): Promise<JsonResponse<DashboardModelViewModel[]>> {
  const { q, page = 0, size = 50, sortBy = "updatedAt", sortOrder = -1 } = req.params;

   // ...

  /** Throwing exceptions */
  if(!dashboard) {
    throw new NotFoundError("Dashboard not found");
  }

   /** Return status/data/headers */
  return {
    status: 200 // optional if 200
    body: dashboard.toViewModel(),
    headers: {
      totalcount: dashboardCount,
    }
  };
}

JsonResponse<T> is the return type. Setting a request handler to return it will validate that the responses are matching the intended response type. E.g. Promise<JsonResponse<DashboardModelViewModel[]>>. However, using res and next is also possible, they are passed in as second and third arguments to the requestHandler function.

Request schema

Since types are not an actual entity in javascript, they have to be referenced by name (string). Exporting a constant with the name of the type is the easiest way to do this (see export const GET_DASHBOARDS_REQUEST_SCHEMA = "GetDashboardsRequestSchema"; below). Not that the name must match the name of the file in ./api/schemas. Having an export inside the schema file makes it easier to navigate to the schema from the endpoint file (e.g. ctrl/cmd + click. Whereas just using a string mean you would have to search for it manually).

The conversion is done by typescript-json-schema and supports annotations for things such as max, min etc, read more about how to annotate types here.

They can be exported as:

export const GET_DASHBOARDS_REQUEST_SCHEMA = "GetDashboardsRequestSchema";

/** Query params */
export type GetDashboardsRequestSchema = {
  q?: string;

  sortBy?: "name" | "createdAt";

  /**
   * @minimum -1
   * @maximum 1
   */
  sortOrder?: string;

  /** Number */
  size?: string;

  /** Number */
  page?: string;
};

Is translated into, at run time:

export const GetDashboardsRequestSchema = {
  type: "object",
  description: "Query params",
  properties: {
    q: {
      type: "string",
    },
    sortBy: {
      type: "string",
      enum: ["name", "createdAt"],
    },
    sortOrder: {
      type: "string",
      minimum: -1,
      maximum: 1,
    },
    size: {
      type: "string",
      description: "Number",
    },
    page: {
      type: "string",
      description: "Number",
    },
  },
};

Response schema

import { DashboardModel } from "../../models/DashboardModel";

export const GET_DASHBOARDS_RESPONSE_SCHEMA = "GetDashboardsResponseSchema";

export type GetDashboardsResponseSchema = DashboardModel[];

Json schema setup

import { setupApiInterface } from "hiot-api-interface";

const started = hiot
  .startApp({ logger, onUncaughtException: handleException, handleException })
  .then((locator)=>{
    await setupApiInterface({
      port: PORT,
      apiVersion: "v1",
      serviceLogLevel: "info",
      serviceName: "visualisation-svc",
      typescript: true,
    });

    routes();

    return locator;
  }) 
  .then(waitFor)
  .then(db)
  .then(shutdown)
  .then(setDatabaseIndexes)
  .catch(hiot.failed(logger));

routes.ts

import getDashboardByIdEndpoint from "./dashboard/getDashboardByIdEndpoint";

export default function () {
  getDashboardsEndpoint();
}

This is equal to doing (since all the endpoint details are set in the endpoint file):

import getDashboardByIdEndpoint from "./dashboard/getDashboardByIdEndpoint";

export default function (server: restify.Server) {
  /*
   * @api [get] /dashboards
   * tags:
   *   - dashboards
   * summary: "Get dashboards"
   * description: "Gets all dashboards"
   * responses:
   *   "200":
   *     description: "The dashboards found"
   *     schema:
   *       type: "object"
   *       description: "Query params"
   *       // ...the rest of the schema as a manual swagger comment
   */
  api.get(
    route(GET_DASHBOARDS_PATH),
    validate(GetDashboardsRequestSchema),
    mustBe.authorized(GET_DASHBOARDS_ACTIVITY),
    getDashboardsEndpoint
  );
}

Testing


### Through sandbox

```typescript
describe("getDashboardsEndpoint", () => {
  it("should...", async () => {
    const { status, body, headers } = await box.api
      .get(`/v1${GET_DASHBOARDS_PATH}`)
      .set(AUTH_USER_HEADER, user.userId)
      .set(AUTH_ACTIVITIES_HEADER, GET_DASHBOARDS_ACTIVITY);

    // ...
  });
});

Directly on handler

If an endpoint needs to be tested directly, it can be done like this:

import getDashboardByIdEndpoint from "../api/dashboard/getDashboardByIdEndpoint";

describe("getDashboardsEndpoint", () => {
  it("should...", async () => {
    const { status, body, headers } = await getDashboardsEndpoint.requestHandler({
      params: {
        q: "test",
        page: "0",
        size: "50",
        sortBy: "updatedAt",
        sortOrder: "-1",
      },
      user: {
        userId: user.userId,
        activities: GET_DASHBOARDS_ACTIVITY,
      },
    });

    // ...
  });
});

The export of the endpoint file is both a function for registering the endpoint and an object with the request handler.

Publishing

Prerequisites:

  • You have to be part of the @hiotlabs organization on npm
  • You have to be logged in to npm

Then, in root, run:

// Install dependencies
yarn install

// Build
tsc

// Make sure tests pass
npm t

// Publish
npm publish --access public

Adding new directories to the project (@hiotlabs/hiot-api-interface)

  • Create folder
  • Add index.ts file in the folder
    • This file will be responsible for exporting functions.
  • Add one entry for .js, .js.map and .d.ts for the folder to package.json's files array, e.g. utils/**/*.js, utils/**/*.js.map and utils/**/*.d.ts
  "files": [
    "**/*.d.ts",
    "./index.js",
    "lib/**/*.js",
    "lib/**/*.js.map",
    "lib/**/*.d.ts",
    "errors/**/*.js",
    "errors/**/*.js.map",
    "errors/**/*.d.ts",
    "constants/**/*.js",
    "constants/**/*.js.map",
    "constants/**/*.d.ts",
    "utils/**/*.js",
    "utils/**/*.js.map",
    "utils/**/*.d.ts"
  ],