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

simpler-server

v0.3.0

Published

Simpler is a simple Node.js server, designed to rapidly provide a base to start your server projects.

Downloads

16

Readme

Simpler

Node.js License

Simpler é um framework de servidor Node.js leve e personalizável. Ele permite definir rotas, lidar com variáveis de caminho dinâmicas, parâmetros de consulta e servir arquivos estáticos com facilidade.

Instalação

Para instalar o Simpler, você pode usar o npm:

npm install simpler

Uso

Criando uma Instância

Você pode criar uma instância do Simpler importando-o e, opcionalmente, habilitando logs verbosos:

import Simpler from "simpler";

const simpler = new Simpler(true); // Habilitar logs verbosos

Definindo Rotas

Você pode definir rotas usando os métodos addRoute ou addRoutes. A mesma rota pode lidar com múltiplos métodos, e você pode definir variáveis de caminho dinâmicas usando :. A função de callback para uma rota sempre receberá req, res, body, pathVariables e queryParams.

pathVariables e queryParams são objetos com os valores dos parâmetros de caminho e de consulta.

Simpler possui um método de resposta que executará os métodos de resposta padrão. Você pode definir uma resposta via Simpler ou diretamente em res. Abaixo estão alguns exemplos e seus equivalentes:

// Retornando com Simpler
simpler.response(
  res,
  200,
  { "Content-Type": "application/json" },
  JSON.stringify(parsedBody)
);

// Equivalente retornando diretamente com res
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(parsedBody));

// Retornando com Simpler
simpler.response(res, 200, { "Content-Type": "text/html" }, data);

// Equivalente retornando diretamente com res
res.writeHead(200, { "Content-Type": "text/html" });
res.end(data);

Abaixo, você encontrará exemplos de como usar o método addRoute.

simpler.router.addRoute(
  "/test",
  ["POST", "GET"],
  (_req, res, body, _pathVariables, _queryParams) => {
    const parsedBody = JSON.parse(body);
    simpler.response(
      res,
      200,
      { "Content-Type": "application/json" },
      JSON.stringify(parsedBody)
    );
    return;
  }
);

simpler.router.addRoute(
  "/test/:id",
  ["POST", "GET"],
  (_req, res, body, _pathVariables, _queryParams) => {
    const parsedBody = JSON.parse(body);
    /*
      Exemplo de variáveis de caminho:
      pathVariables: {
      "id": "{valor}"
      }
    */
    simpler.response(
      res,
      200,
      { "Content-Type": "application/json" },
      JSON.stringify(parsedBody)
    );
    return;
  }
);

simpler.router.addRoute(
  "/test/:id/:xpto",
  ["POST", "GET"],
  (_req, res, body, _pathVariables, _queryParams) => {
    const parsedBody = JSON.parse(body);
    /*
      Exemplo de variáveis de caminho:
      pathVariables: {
      "id": "{valor1}",
      "xpto": "{valor2}",
      }
    */
    simpler.response(
      res,
      200,
      { "Content-Type": "application/json" },
      JSON.stringify(parsedBody)
    );
    return;
  }
);

Servindo Arquivos Estáticos

Você pode configurar o Simpler para servir arquivos estáticos de um diretório usando os métodos addStaticDirectory ou addStaticDirectories. Além disso, você pode carregar uma página HTML em uma rota.

import path from "path";
import { readFile } from "fs";

simpler.router.addStaticDirectory("./src/static");

simpler.router.addRoute("/static", ["GET"], (_req, res) => {
  const testePath = path.join(__dirname, "static", "test.html");
  readFile(testePath, (err, data) => {
    if (err) {
      simpler.response(
        res,
        500,
        { "Content-Type": "text/plain" },
        "500 Internal Server Error"
      );
      return;
    }

    simpler.response(res, 200, { "Content-Type": "text/html" }, data);
  });
});

Carregando arquivos

Você pode carregar arquivos com simpler utilizando a função loadFile, a função recebe um res a o caminho relativo para o arquivo.

Abaixo você encontrará um exemplo de como utilizar-la.

simpler.router.addRoute("/static-page", ["GET"], (_req, res) => {
  simpler.loadFile(res, "./src/static/teste.html");
});

Redirecionando

Você pode redirectionar rotas com a função redirect, ela recebe um parametro res e a url relativa para onde deve-se redirecionar o usuário.

Abaixo você encontrará um exemplo de como utilizar-la.

simpler.router.addRoute("/redir", ["GET"], (_req, res) => {
  simpler.redirect(res, "/static-page");
});

Lidando com Erros

Você pode lidar com erros de maneira customizada utilizando a função errorHandler.setCustomErrorHandler. A função recebe uma função como parâmetro que receberá res e error como parâmetros.

Abaixo você encontrará um exemplo de como utilizar-la.

simpler.errorHandler.setCustomErrorHandler(
  (res: ServerResponse, error: Error) => {
    res.writeHead(400, {
      "Content-Type": { "Content-Type": "application/json" },
    });
    res.end(JSON.stringify({ message: "Custom Error", error: error.message }));
  }
);

Iniciando o Servidor

Para iniciar o servidor, use o método listen. Você pode especificar o número da porta, que por padrão é 3000 se não for fornecido.

simpler.listen(3001);

Exemplo de Implementação

Aqui está um exemplo de uma configuração completa usando Simpler:

import { readFile } from "fs";
import Simpler from "simpler";
import path from "path";

const simpler = new Simpler(true);

simpler.router.addRoute("/test", ["POST", "GET"], (_req, res, body) => {
  const parsedBody = JSON.parse(body);
  simpler.response(
    res,
    200,
    { "Content-Type": "application/json" },
    JSON.stringify(parsedBody)
  );
  return;
});

simpler.router.addRoute(
  "/test/:id",
  ["POST", "GET"],
  (_req, res, body: string, _pathVariables, _queryParams) => {
    const parsedBody = JSON.parse(body);
    simpler.response(
      res,
      200,
      { "Content-Type": "application/json" },
      JSON.stringify(parsedBody)
    );
    return;
  }
);

simpler.router.addRoute(
  "/test/:id/:xpto",
  ["POST", "GET"],
  (_req, res, body, _pathVariables, _queryParams) => {
    const parsedBody = JSON.parse(body);
    simpler.response(
      res,
      200,
      { "Content-Type": "application/json" },
      JSON.stringify(parsedBody)
    );
    return;
  }
);

simpler.router.addStaticDirectory("./src/static");

simpler.router.addRoute("/static-page", ["GET"], (_req, res) => {
  simpler.loadFile(res, "./src/static/teste.html");
});

simpler.errorHandler.setCustomErrorHandler(
  (res: ServerResponse, error: Error) => {
    res.writeHead(400, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ message: "Custom Error", error: error.message }));
  }
);

simpler.listen(3001);

Seguindo estas instruções, você pode configurar e executar seu servidor Simpler, configurar rotas, lidar com variáveis de caminho dinâmicas, parâmetros de consulta e servir arquivos estáticos com facilidade.

Licença

Este projeto é licenciado sob a licença MIT. Consulte o arquivo LICENSE para mais detalhes.

Outras versões

Readme em Inglês (EN)