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

expressa-folder

v1.1.0

Published

file-based design-pattern to organize expressa & express REST/db middleware

Downloads

22

Readme

file-based design-pattern to organize expressa & express REST/db middleware

Build Status

Usage

require('expressa-folder')(expressa, app)
expressa.addListener('ready', 100, >(){
  expressa.folderDir = __dirname+"/lib"
  expressa.initFolder('foo')      // will require expressa db/REST-listener code if collection 'foo' exist
  expressa.initFolder('foo/bar')  // will setup custom express point
  // optional: generate REST client for in the browser at /api/client.js
  require('expressa-client').middleware({expressa:expressa,  app:app}) 
})

This will automatically fetch the following files if present:

| file | expressa listener | creates express endpoint | note | | - | - | - | - | | lib/foo/get.js | yes | no | requires data/collection/foo.js to exist | | lib/foo/post.js | yes | no | requires data/collection/foo.js to exist | | lib/foo/put.js | yes | no | requires data/collection/foo.js to exist | | lib/foo/delete.js | yes | no | requires data/collection/foo.js to exist | | lib/foo/schema.js | yes | no | requires data/collection/foo.js to exist | | lib/foo/functions.js | no | no | all db objects will inherit these functions | | lib/foo/swagger.js | no | no | only when expressa-swagger is installed | | lib/foo/bar/get.js | no | yes | bare express endpoint without expressa schema-validation| | lib/foo/bar/swagger.js | no | no | only when expressa-swagger is installed |

Example: lib/foo/get.js

module.exports = function(expressa, app){
  return function(req, collection, doc, resolve, reject) {
    // do stuff with the response data (doc)
    resolve(doc)
  })
}

Example: lib/foo/functions.js

module.exports = function(expressa, app){
  return {
    addPropertyFoo: () => {
      this.foo = "bar"
    }
  }
}

Now you can easily access helper functions on the server:

expressa.db.foo.find({})
.then( function(items){
  items.map( (i) => i.addPropertyFoo() )
})

Example: lib/foo/bar/get.js (bare express)

module.exports = function(expressa,app){
  return function(req, res, next){
			res.writeHeader(200, {"Content-Type":"application/json"})
			res.end( JSON.stringify({"foo":"bar"}) )
  }
}

Voila..this will automatically setup a 'foo/bar' express-endpoint

Example: robust custom endpoint

NOTE: The non-expressa endpoint above, is a simple express endpoint. Unfortunately express endpoints have zero input validation (unlike expressa endpoints).

Here's how to do it for express as well..let assume we want the user to submit to a mailinglist:

// lets add the endpoint
expressa.initFolder('users/mailinglist')

And now lets write lib/users/mailinglist/post.js:

var typeshave = require('typeshave') // json schema validator
var typesafe  = typeshave.typesafe

var schema = require('./../../../../data/collection/users.json').schema
schema.required = ["firstname", "email"] // overrule required properties

module.exports = function(expressa, app ){

  return function(req, res, next){

    res.writeHeader(200, {"Content-Type":"application/json"})

    try{ 

      typesafe(schema, function(){

        expressa.db.users.find({email:req.body.email})
        .then( function(user){
          if(user.length != 0) throw "user "+req.body.email+" already exist"
          return expressa.db.users.create( req.body )
        })
        .then(function(id){
          res.end( JSON.stringify({code:0, id:id}) )
        })
        .catch(function(err){
          res.end( JSON.stringify({"code":1, error:err}) )
        })

      })(req.body) 

    }catch(e){
      return res.end( JSON.stringify({"code":2, error:e}) )
    }

  }
}

Boom...if we would now post {} to our endpoint:

$ curl -X POST 'http://localhost:3001/api/users/mailinglist' --data '{}'

Then the server will reply:

{ data: {},
  errors:
   { message: 'Missing required property: email',
     dataPath: '',
     schemaPath: '/required/0',
     subErrors: null },
  schema:
   { type: 'object',
     additionalProperties: false,
     properties:
      { meta: [Object],
        email: [Object],
        password: [Object],
        firstname: [Object],
        lastname: [Object],
        roles: [Object] }
     required: [ 'email', 'firstname' ],

Example: lib/foo/swagger.js

This will add (or overwrite) swagger documentation, generated at url /api/doc using expressa-admin:

module.exports = {
  "/foo":{
    "get":{
      "parameters": [
        {
          "in": "body",
          "name": "payload",
          "description": "", 
          "required": true,
          "schema": {
            "type": "object",
            "required":["id_user"],                  // see swagger
            "properties": {                          // documentation
              "id_user":{
                "required":true, 
                "type":"string",
                "default":"lLK34LK" 
              }
            }
          }
        }    
      ],
      "responses": { },
      "tags": [ "users" ],
      "summary": "Lorem ipsum"
    }
  }
}