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

apidoc-creator

v1.3.0

Published

Crea el apidoc de las rutas de un servicio web según el formato que establece ApidocJS.

Downloads

17

Readme

Apidoc Creator

La forma tradicional de documentar servicios web RESTFUL, es escribir la descripción de la ruta en forma de comentario en el caso de ApidocJS o en un fichero con formato JSON en el caso de Swagger.

ApidocJS es muy flexible al momento de describir la ruta de un servicio, sin embargo, describir las rutas en forma de comentarios no es la adecuada si se quiere automatizar este proceso.

Apidoc Creator utiliza ApidocJS para crear la documentación y ofrece un sistema diferente para describir las rutas, fácil de implementar. Para describir los datos de entrada y salida, utiliza la librería Field Creator.

Características

  • Devuelve la descripción de una ruta en formato de texto plano, según el formato que establece ApidocJS.
  • Devuelve la descripción de un modelo Sequelize en formato MD (MarkDown).

Propiedades soportadas:

| Propiedad | Descripción | |------------------|----------------------------------------------------------| | name | Nombre asignado a la ruta. | | method | Método HTTP para acceder al recurso. | | path | Ruta del recurso (URI). | | group | Grupo al que pertenece la ruta. | | version | Versión de la ruta. | | description | Descripción de la ruta. | | input | Datos de entrada. Objeto de tipo FieldGroup. | | output | Datos de salida. Objeto de tipo FieldGroup. | | inputExamples | Ejemplos de datos de entrada. | | outputExamples | Ejemplos de datos de salida. | | permissions | Lista de todos los roles que pueden acceder al recurso. | | sampleRequest | Dirección URL de la ruta para probar una petición. |

Propiedades input y output

const INPUT = {
  headers : FIELD,
  params  : FIELD,
  query   : FIELD,
  body    : FIELD
}

const OUTPUT = FIELD // Siempre sera body

Para crear los objetos input y output, se recomienda utilizar la librería field-creator.

Función onCreate

Esta función puede utilizarse para realizar una tarea de forma automática cada vez que se defina una ruta.

function onCreate (route) {
  console.log(route.apidoc)
  // TODO
}

const router = Apidoc.router(onCreate)

router.GET('/api/v1/libros', { ... })
router.GET('/api/v1/libros/:id', { ... })
router.POST('/api/v1/libros', { ... })
router.PUT('/api/v1/libros/:id', { ... })
router.DELETE('/api/v1/libros/:id', { ... })

Instalación

Para instalar sobre un proyecto, ejecutar el siguiente comando:

$ npm install --save apidoc-creator

Ejemplo 1. Descripción de modelos

const { Apidoc } = require('apidoc-creator')
const { Field }  = require('field-creator')

LIBRO = sequelize.define('libro', {
  id     : Field.ID({ comment: 'ID del libro.' }),
  titulo : Field.STRING({ comment: 'Título del libro.', example: 'El gato negro' }),
  precio : Field.FLOAT({ comment: 'Precio del libro. [Bs]' }),
  estado : Field.ENUM(['ACTIVO', 'INACTIVO'], { comment: 'Estado del registro.' })
}, {
  comment: 'Representa a una obra literaria.'
})
const markdown = Apidoc.model(LIBRO)
console.log(markdown)
/*

### **libro**

Representa a una obra literaria.

| Atributo           | Tipo de dato                           | Descripción                    |
|--------------------|----------------------------------------|--------------------------------|
| `id` [ PK ]        | `Integer`                              | ID del libro.                  |
| `titulo`           | `String`                               | Título del libro.              |
| `precio`           | `Float`                                | Precio del libro. [Bs]         |
| `estado`           | `Enum=ACTIVO,INACTIVO`                 | Estado del registro.           |

*/

Ejemplo 2. Descripción de rutas.

const { Apidoc }      = require('apidoc-creator')
const { Field, THIS } = require('field-creator')
const express         = require('express')

const app = express()

function onCreate (route) {
  app[route.method](route.path, route.controller)

  console.log(route.apidoc)
  /**
  * @api {post} /libros crearLibro
  * @apiName crearLibro
  * @apiGroup Libro
  * @apiDescription Crea un libro.
  * @apiVersion 1.0.0
  * @apiParam (Datos de entrada - body) {String} titulo Título del libro. <br><strong>len: </strong><code>0,255</code>
  * @apiParam (Datos de entrada - body) {Float} precio Precio del libro. [Bs] <br><strong>isFloat: </strong><code>true</code>, <strong>min: </strong><code>0</code>, <strong>max: </strong><code>1e+308</code>
  * @apiParam (Datos de entrada - body) {Enum} estado Estado del registro. <br><strong>isIn: </strong><code>ACTIVO,INACTIVO</code>
  * @apiParamExample {json} Ejemplo Petición
  * {
  *   "titulo": "El gato negro",
  *   "precio": 12.99,
  *   "estado": "ACTIVO"
  * }
  * @apiSuccess (Respuesta - body) {Integer} [id] ID del libro.
  * @apiSuccess (Respuesta - body) {String} [titulo] Título del libro.
  * @apiSuccess (Respuesta - body) {Float} [precio] Precio del libro. [Bs]
  * @apiSuccess (Respuesta - body) {Enum} [estado] Estado del registro.
  * @apiSuccessExample {json} Respuesta Exitosa: 200 Ok
  * HTTP/1.1 200 Ok
  * {
  *   "id": 1,
  *   "titulo": "El gato negro",
  *   "precio": 12.99,
  *   "estado": "ACTIVO"
  * }
  */
}
const router = Apidoc.router(onCreate)

router.GET('/libros', {
  description : 'Crea un libro.',
  name        : 'crearLibro',
  group       : 'Libro',
  input       : {
    body: Field.group(LIBRO, {
      titulo : THIS({ allowNull: false }),
      precio : THIS({ allowNull: false }),
      estado : THIS({ allowNull: false })
    })
  },
  output: Field.group(LIBRO, {
    id     : THIS(),
    titulo : THIS(),
    precio : THIS(),
    estado : THIS()
  }),
  controller: (req, res, next) => {
    return res.status(200).json({ msg: 'ok' })
  }
})