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

api-controller-express

v1.2.3

Published

A library which creates express routes based on collections.

Downloads

7

Readme

Api Controller

A controller library which creates collection based routes and handles JSON Schema based data validations.

Collection Structure

.
├── collections-folder/
│   ├── collection-one
│   │   └── index.js
│   ├── collection-two
│   │   └── index.js
│   └── collection-three
│       └── index.js
└── server.js

Usage

NPM

Library in action

  • The file where you'll use the api-controller
    /**
    * Controller which goes through all collections
    * and create POST routes based on operations
    * and validate data based on schemas
    *
    * @param {Object} params
    * @param {string} params.collectionPath - path where all your collections are stored
    * @param {string} params.baseUrl - Base url set to your collection
    * @param {Application} params.app - Express instance
    */
      
    controller({ collectionPath: "path-to-your-collections", baseUrl: "/sample-base-url", app });
    
  • A Collection file format - collection-name-one/index.js
    • ✅ CRUD Operation for a collection.
    • ✅ Operation and Scope level schema validation.
    • 🌟 Re-use operations without using rest call.
      // JSON Schema handled by AJV -- https://json-schema.org/
      const schema = {
          read: {
              type: 'object',
              properties: {
                  user: { type: 'object' },
              },
              required: ['user'],
          },
          // Schema for scope support
          read_download: {
              type: 'object',
              properties: {
                  user: { type: 'object' },
                  dataobj: { type: 'object' },
              },
              required: ['dataobj', 'user'],
          },
      };
      
      module.exports = (app) => {
          // This is where you'll be writing all logic code.
          const operations = {
              read: async (req) => {
                  console.log('inside read of collection-one');
      
                  // Get scope from the route
                  const { scope } = req.params;
      
                  if (scope === 'xyz') {
                      // Logic to read a data based on scope xyz
                      return { status: 'success', data: 'xyz_data' };
                  }
      
                  if (scope === 'download') {
                      // logic to read data and send data as a file.
                      // res.status(200).download("pathoffile","file.txt")
                      return { resMethod: 'download', resParams: [path.join(__dirname, './index.js'), 'index.js'] };
                  }
      
                  // logic to read data without scope.
                  // res.status(200).json({ status: 'success', data: 'mydata' })
                  return { status: 'success', data: 'mydata' };
              },
              create: async (req) => {
                  console.log('inside create of collection-one');
      
                  const data = req.body;
                  // Logic to write a data into db.
                  // res.status(500).json({ status: "unsuccess" })
                  return { status: '201' };
              },
              update: async (req) => {
                  console.log('inside update of collection-one');
      
                  const data = req.body;
                  // update data logic
                  // res.status(200).json({ status: "success", message: 'data updated with custom status code'  })
                  return { status: 'success', message: 'data updated with custom status code' };
              },
              delete: async (req) => {
                  console.log('inside delete of collection-one');
      
                  // delete a data form db
                  // res.status(200).json({ status: 'success' })
                  return { status: 'success' };
              },
          };
          return {
              operations,
              schema,
          };
      };

Routes

  • The controller then creates following routes.
      POST http://localhost:port/<base-url-you-passed-in-controller>/<foldername-under-collectionPath>/<operation>/<scope>

    Here scope is Optional

    • So for above code example the controller creates following routes
      • POST http://127.0.0.1:3000/sample-base-url/collection-name-one/read/:scope
      • POST http://127.0.0.1:3000/sample-base-url/collection-name-one/update/:scope
      • POST http://127.0.0.1:3000/sample-base-url/collection-name-one/create/:scope
      • POST http://127.0.0.1:3000/sample-base-url/collection-name-one/delete/:scope