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

astad

v0.2.16

Published

astad is a nodejs framework for api and web development

Downloads

11

Readme

Astad

Quick Start with Koajs

import { HttpApp, HttpKoa, HttpCors } from 'astad';
import Koa from 'koa';
import koaLogger from 'koa-logger';
import { koaBody } from 'koa-body';
// if required otherwise remove it
import ejs from 'ejs';

// config file
import { Config } from './config.js';

// main files
import web from './http/web/index.js';
import api from './http/api/index.js';

// koa instance
const app = new Koa();
// add middleware directly to koa
app.use(koaLogger());
app.use(koaBody({ multipart: true, formidable: { keepExtensions: true } }));

// create http app
const httpApp = new HttpApp({
  use: new HttpKoa(app),
  conf: Config,
});

// cors middleware
httpApp.use(new HttpCors());

// view engine if required
httpApp.viewEngine(new class {
  async render(template: string, data: Record<any, any> = {}) {
    return await ejs.renderFile(`./resources/views/${template}.ejs.html`, data);
  }
});

// register routers
httpApp.router(web); // web router
httpApp.router('/api', api); // api router

// start server
httpApp.listen();

Config file example

import { config } from 'dotenv';
import { Conf } from 'astad/conf';

config({
  path: '.env',
});

export const Config = new Conf();

Router example

Web router file

import { HttpRouter } from 'astad/http';

const web = new HttpRouter();

web.get('/', async ctx => {
  await ctx.view('welcome');
});

export default web;

Below is api router file

import { HTTP_KEY_REQ_ID, HttpRouter } from 'astad/http';

const api = new HttpRouter();

api.get('/', async ctx => {
  ctx.json({
    name: 'Astad Example',
    ver: '0.1.0',
    reqid: ctx.value(HTTP_KEY_REQ_ID),
  });
});

export default api;

Console application

import { Astad, AstadContext, AstadCompose } from 'astad';

class TestCommand {
  // note: signature is important, as register command will use this property 
  signature: string = "test";

  description: string = "This is test command!";

  compose() {
    const command = new AstadCompose(this.signature);
    return command;
  }

  async handle(ctx: AstadContext) {
    ctx.info('This is test command!');
  }
}

const cmd = new Astad();
cmd.register(new TestCommand);
await cmd.handle();

Container example

import { Container, ContainerScope } from 'astad/container';

const container = new Container('default');

container.register({
  id: 'static value',
  scope: ContainerScope.Value,
  value: 'Any static value',
});

container.register({
  id: 'static date',
  scope: ContainerScope.Singleton,
  value: () => new Date(),
});

container.register({
  id: 'current date',
  scope: ContainerScope.Transient,
  value: () => new Date(),
});

// only available within context
container.register({
  id: 'context date',
  scope: ContainerScope.Contextual,
  value: () => new Date(),
});

console.log(container.resolve('static value')); // will print "Any static value"
console.log(container.resolve('static date')); // will print same date not matter how many times you resolve
console.log(container.resolve('static date')); // will print same date not matter how many times you resolve
console.log(container.resolve('current date')); // always give current data
console.log(container.resolve('current date')); // always give current data

Testing

Testing routes, can use with any testing tool

import t from 'tap';
import { TestHttpRouter } from 'astad/testing';

import routes from './api.js';

const testroute = TestHttpRouter(routes);

function createRequest(
  method: string,
  path: string,
  body?: Record<string, any>,
) {
  const req: any = {
    method: method,
    path: `/api${path}`,
    body,
    headers: { accept: 'application/json' },
  };

  if (body) {
    req.headers['content-type'] = 'application/json';
  }

  return testroute.req(req);
}

t.test('route', async t => {
  const res = await createRequest('GET', '/').exec();
  t.equal(res.status, 200);
  const data = res.json();
  t.hasOwnProp(data, 'name');
});

Testing services

import t from 'tap';
import { TestMinimalContext } from 'astad/testing';
import Service from './service.js';

// depends on service, if your service need context or your are using contextual container scope
const ctx = new TestMinimalContext();

t.test('service', async t => {
  await ctx.run(async () => {
    const service = new Service();
    const data = await service.test();
    t.ok(data);
  })
});

TODO

  • http: should consider accept header
  • http: should compose or translate error to response
  • http: improve throw in context, should accept error and custom inputs
  • http/cors: should allow vary header configuration, for asset caching
  • docs: automate documentation

In-progress

  • events handler
  • background queue
  • data mapper
  • templating
  • testing

Bugs

  • handle duplicate middlewares in router, should only have unique middlewares

Issue Notes

Node.js[https://nodejs.org/api/stream.html#class-streamreadable] One important caveat is that if the Readable stream emits an error during processing, the Writable destination is not closed automatically. If an error occurs, it will be necessary to manually close each stream in order to prevent memory leaks.

The process.stderr and process.stdout Writable streams are never closed until the Node.js process exits, regardless of the specified options.

Doc Notes

  • use "Deprecated since: version"
  • use "Added: version"