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

@kodasoftware/api

v0.2.0

Published

A library for create Node, Koa-based applications.

Downloads

8

Readme

Koda Software API Library

A library for create Node, Koa-based applications. It facilitates both HTTP server and serverless exports of your APIs.

Using this library

In order to use this library you should first create your application using the factory function. (This example uses the config library):

index.ts

import { application } from './app';
import configuration from 'config'

// Start the server
const config = configuration.util.toObject();
try {
  application.start({ port: config.app.port });
} catch (err) {
  application.end();
}

// Or you can export as a serverless handler instead with one of the below examples - simple!
// AWS - Lambda
// export const handler = application.serverless({ provider: 'aws' });

// Azure - Function
// export const nameOfFunction = application.serverless({ provider: 'azure' });

// Google Cloud - Cloud Function
// application.serverless({ provider: 'gcloud' });

app.ts

import { createApplication, generateSwaggerSpec } from '@kodasoftware/api';
import configuration from 'config'

import { AccountService, CoffeeService } from './lib/services';
import { accountRouteFactory, coffeeRouteFactory } from './routes';

const config = configuration.util.toObject();
export const application = createApplication({
  config: {
    name: config.app.name,
    logLevel: config.log.level,
    // This attaches services to the request context, accessible in a middleware via `ctx.services`
    services: {
      account: new AccountService(),
      coffee: new CoffeeService(),
    },
  },
  cors: { origin: config.cors.origin },
  // Specify koa options constructor
  koa: {},
  // Specify options for koa-body
  body: {},
  swagger: {
    spec: generateSwaggerSpec({
      definition: {
        info: {
          title: config.app.name,
          version: config.app.version,
        },
      },
    }),
  },
});

application.use(accountRouteFactory().attach());
application.use(coffeeRouteFactory().attach());

lib/services.ts

export class AccountService {
  public async retrieveAccounts() {
    return fetch('https://api.sampleapis.com/fakebank/accounts').then(res =>
      res.json()
    );
  }
}

export class CoffeeService {
  public async retrieveCoffee(type: 'hot' | 'iced') {
    return await fetch(
      new URL(`https://api.sampleapis.com/coffee/${type}`)
    ).then(res => res.json());
  }
}

middlewares.ts

import type { Middleware } from '@kodasoftware/api';

import type { AccountService, CoffeeService } from '../lib';

interface Account {
  transactionDate: string;
  description: string;
  category: string;
  debit: number | null;
  credit: number | null;
  id: number;
}

export function accountMiddlewareFactory(): Middleware<
  Account[],
  { account: AccountService }
> {
  return async function accountMiddleware(ctx) {
    ctx.body = await ctx.services.account.retrieveAccounts();
    ctx.status = 200;
  };
}

interface Coffee {
  title: string;
  description: string;
  ingredients: string[];
  image: string;
  id: number;
}

export function coffeeMiddlewareFactory(): Middleware<
  Coffee,
  { coffee: CoffeeService }
> {
  return async function exampleMiddleware(ctx) {
    const type = ctx.params.type as 'hot' | 'iced';
    ctx.body = await ctx.services.coffee.retrieveCoffee(type);
    ctx.status = 200;
  };
}

routes.ts

import { Router, schemaMiddlewareFactory } from '@kodasoftware/api';

import { accountMiddlewareFactory, coffeeMiddlewareFactory } from '../middlewares';

/**
 * @openapi
 * /accounts:
 *  get:
 *    tags:
 *      - Account
 *    description: Retrieve bank accounts
 *    responses:
 *      200:
 *        description: Return 200 response
 *        content:
 *          application/json:
 *            schema:
 *              type: array
 */
export function accountRouteFactory() {
  const router = new Router();
  router.get('accounts', '/accounts', accountMiddlewareFactory());
  return router;
}

/**
 * @openapi
 * /coffee/{type}:
 *  post:
 *    tags:
 *      - Coffee
 *    description: Retrieve types of coffee
 *    parameters:
 *      - name: type
 *        in: path
 *        description: The type of coffee you want to retrieve
 *        required: true
 *        schema:
 *          type: string
 *          enum:
 *            - hot
 *            - iced
 *    responses:
 *      200:
 *        description: Return 200 response
 *        content:
 *          application/json:
 *            schema:
 *              type: array
 */
export function coffeeRouteFactory() {
  const router = new Router();
  router.post(
    'coffee',
    '/coffee/:type',
    schemaMiddlewareFactory({
      schema: {
        path: {
          type: 'object',
          properties: {
            type: {
              type: 'string',
              enum: ['hot', 'iced'],
            },
          },
          required: ['type'],
        },
      },
      expose: true,
    }),
    coffeeMiddlewareFactory()
  );
  return router;
}

Enjoy!