m Feathers - CRUD api framework

Key Points

  1. Feathers can generate CRUD api frameworks based on simple domain models
  2. CRUD services are automatically used in the framework via http calls
  3. all services can have before and after hooks to customize the request and response
  4. Feathers has MANY available plugins for any app scenario
  5. consider creating a VUE app generator for the models in the feathers app


Quick overview of Feathers - 2023

Key Issues

  1. Lacks the view join capabilities of Grails
  2. Lacks the ability to generate SCRUD front-end like Grails ( need to use Marmelab EOS )
  3. If you define separate apps based on role issues exist
    1. can't easily do a single sign-on for a user across multiple Feathers apps without SSO, Openid Connect
      or create 1 app with multiple roles and a single token with appropriate features enabled
    2. to use same services in multiple apps must redefine the services in each app ( need a redirect to a 2nd app to run the service, return the results )
  4. more

References

Reference_description_with_linked_URLs____________________________Notes__________________________________________________________________


https://drive.google.com/open?id=1gtGNXt1mBN-UOKVboB2l3cRhUZLr3zz6Nodejs cheat sheet
https://drive.google.com/open?id=122X-MwR-7LctVRuWjefGduliSZf_Acs1Nodejs book - free code camp
https://drive.google.com/open?id=1vlz4U_-KgmDf-IyeXd4W1JxL-AZz5vHcBeginner Nodejs book
https://drive.google.com/open?id=1RkkEkEIV1-BMY-23tnPw93LVYDbD-Dn8Beginner Nodejs book part 2 - Craftsman
https://drive.google.com/open?id=0BxqKQGV-b4WQY3pIZV8ycHlISEkNpm Beginners Guide
Frameworks






















































https://zetcode.com/javascript/nodeconfig/Node module to manage environment configurations *


Feathers references


https://feathersjs.com/guides/
FeathersJS in 100 seconds video 
Build Rest API with Authentication using Feathers JS << great 40 min intro !!
https://github.com/feathersjs/feathers
https://docs.feathersjs.com/feathers docs
https://feathersjs.com/api/
https://docs.feathersjs.com/guides/basics/authentication.htmlFeathers docs - authentication
https://feathersjs.com/api/events.html

https://www.sitepoint.com/feathers-js-guide/

Sitepoint Feathers Tutorial - good pdf

Sitepoint Feathers Tutorial - good **

https://gorrion.io/blog/use-feathersjs-to-build-rest-and-socket-io-api

feathers-rest-api-tutorial-gorrion-Use FeathersJS to build REST and Socketio API in no time.pdf

Feathers tutorial for REST, socket.io API server *
https://www.youtube.com/watch?v=8y33WCVkLwcYoutube Feathers video tutorial *
https://docs.feathersjs.com/guides/Feathers guides
https://github.com/LeCoupa/awesome-cheatsheets/blob/master/backend/feathers.jsFeathers cheat sheet
https://github.com/LeCoupa/awesome-cheatsheets/blob/master/backend/feathers.jsFeathers authentication summary nc

https://docs.feathersjs.com/guides/basics/frontend.html#login-and-signup

https://docs.feathersjs.com/guides/frameworks.html#the-feathers-chat

Simple Feathers frontend tutorial for basic chat app

other examples show React, Vue etc frontends

https://docs.feathersjs.com/api/client.htmlfeathers client has many front-end modules for Feathers **
https://github.com/feathersjs/awesome-feathersjs#frontend-frameworksFeathers framework list ***
https://github.com/feathersjs/awesome-feathersjs#official-resourcesFeathers supported resource frameworks


Authentication and RBAC permissions frameworks


https://github.com/feathersjs-ecosystem/feathers-permissions

feathers-permissions source

for a user object, feathers-permissions hook should be used after the authenticate() hook from @feathersjs/authentication.

https://blog.feathersjs.com/access-control-strategies-with-feathersjs-72452268739d

ABAC - Attribute Based Access Control

more flexible than RBAC ( like Fidelity )

https://www.sitepoint.com/feathers-js-guide/Sitepoint tutorial uses standard bearer token ( jwt ) authentication
https://www.npmjs.com/package/feathers-permissions

Feathers-permissions **

flexible role permission models w examples







Web UI frameworks



Reactjs

Figma
https://marmelab.com/react-admin/Marmelab **






Web Sockets

https://www.nodebeginner.org/blog/post/nodejs-tutorial-how-to-work-with-websockets/

https://drive.google.com/open?id=1jdcAQrY3zLP3AiSu0DCSx0w2F38KjDmq

Nodejs Web sockets example with socket.io

use this tutorial for websockets first

https://medium.com/@martin.sikora/node-js-websocket-simple-chat-tutorial-2def3a841b61

file:///C:/Users/Jim%20Mason/Google%20Drive/_docs/howto/js/node/tutorials/web-sockets-nodejs-chat-tutorial-medium.com-Nodejs%20amp%20WebSocket%20%20Simple%20chat%20tutorial.pdf

Web sockets example in Nodejs without Socket.io
https://github.com/websockets/wsSimple to use, blazing fast and thoroughly tested WebSocket client and server for Node.js


Nodejs frameworks


Nodejs tools
https://code.visualstudio.com/docs/nodejs/nodejs-tutorialVSCode for Nodejs tutorial

m Github Hello World Tutorial

m Github scm

Github


Key Concepts



MANY Nodejs basic tips and tutorials

https://www.freecodecamp.org/news/search/?query=nodejs

https://flaviocopes.com/node-read-csv/

Node handook pdf

nodejs-servers-How to Start a Node Server Examples with the Most Popular Frameworks.pdf

nodejs-the-complete-guide-course-at-udemy-.pdf

https://www.freecodecamp.org/news/how-to-build-a-todo-app-with-react-typescript-nodejs-and-mongodb/

https://www.freecodecamp.org/news/create-a-professional-node-express/

https://www.freecodecamp.org/news/node-js-production-checklist/

https://www.freecodecamp.org/news/stripe-and-node-js-4-best-practices-and-examples/


Node.js debug

https://www.freecodecamp.org/news/watch-sockets-with-this-grunt-plugin/

https://www.freecodecamp.org/news/node-js-debugging/

Node AWS

https://www.freecodecamp.org/news/how-to-build-and-deploy-graphql-server-in-aws-lambda-using-nodejs-and-cloudformation/

https://www.freecodecamp.org/news/how-to-reuse-packages-with-aws-lambda-functions-using-amplify/


Feathers Concepts 


Feathers API Services

https://feathersjs.com/api/

Feathers Architecture overview


Feathers Event Support

https://feathersjs.com/api/events.html

Events are the key part of Feathers real-time functionality. All events in Feathers are provided through the NodeJS EventEmitter interface. This section describes


Feathers REST API support

Feathers uses the concept of a Model object for an entity to map to the configured data source.

IF the Model and the data source match on field names for that Entity then the basic CRUD functions of create, update, patch will work without additional code in the API for that entity

IF you need added changes to the data model ( eg calculate fundsAvailable = fundsBalance - fundsAllocatedOrders ) then you need a before hook method to do those added data changes before the write to the data source

Example of a patch method that can get and manage account data before patch executes

   update: [ commonHooks.disallow('external') ],
//    patch: [ commonHooks.disallow('external') ],
    patch: [
      setField({
        from: 'params.account._id',
        as: 'params.query.accountId'
      }),
      commonHooks.iff(
        commonHooks.isProvider('external'),
        async context => { 
          if(context.data) {
            console.log(`context.accounts : ${JSON.stringify(context.accounts)}\n\n`);
            console.log(`context.data : ${JSON.stringify(context.data)}\n\n`);
          };
          let theAccount = await context.service.find({ query: { _id: context.id }, paginate: false });
//          console.log(`theAccount : ${JSON.stringify(theAccount)}\n`)
        }
      ),
      commonHooks.iff(
        commonHooks.isProvider('external'),
        commonHooks.preventChanges(true, 
          'accountId',
          'lastTransactionTxId'
        )
      )
    ],



Feathers Client Authentication ( vs Axios )



Feathers Web Sockets using socket.io for Trade Desk 


example is

  • when you accept my offer to sell energy
  • then my energyBalance and energyAllocatedOffers drop
  • so I can see the change dynamically on my trade desk



Node configuration module to manage config files directory using environment variable NODE_ENV

https://zetcode.com/javascript/nodeconfig/

Node-config tutorial shows how to create configuration files for Node applications with node-config module.

Node-config

Node-config creates configuration files for application deployments.

Node-config allows us to define a set of default parameters and extend them for different deployment environments (development, qa, staging, production, etc.).

The configuration files are located in the default config directory. The location can be overriden with the NODE_CONFIG_DIR environment variable. The NODE_ENV environment variable contains the name of our application's deployment environment; it is development by default.

Node config supports various configuration file formats, including JSON, YAML, properties, or XML. The default configuration file is default.json (or default.yaml, default.xml). If we use a production deployment, then the configuration is loaded from production.json.

Setting up Node-config

First, we install node-config.

$ node -v
v11.5.0

We use Node version 11.5.0.

$ npm init -y

We initiate a new Node application.

$ npm i config

We install node-config with nmp i config.

$ npm i js-yaml

In addition, we install js-yaml for YAML support.

Node-config example

The following example retrieves configuration data with config package.

config/default.json
{
    "app": {
        "port": 3000
    },
    "db": {
        "host": "localhost",
        "port": 27017,
        "name": "ydb"
    }
}

We have default.json in the config directory.

simple.js
const config = require('config');

let appPort = config.get('app.port');
console.log(`Application port: ${appPort}`);

let dbHost = config.get('db.host');
console.log(`Database host: ${dbHost}`);

let dbPort = config.get('db.port');
console.log(`Database port: ${dbPort}`);

let dbName = config.get('db.name');
console.log(`Database name: ${dbName}`);

console.log('NODE_ENV: ' + config.util.getEnv('NODE_ENV'));

We load the config package and get the values with config.get() function. The default deployment type is specified in NODE_ENV.

$ node simple.js
Application port: 3000
Database host: localhost
Database port: 27017
Database name: ydb
NODE_ENV: development

This is the output.

Node-config example II

We change the configuration file to YAML and set a production deployment environment.

config/default.yaml
app:
  port: 3000

db: 
  host: localhost
  port: 27017
  name: ydb

This is default.yaml file.

config/production.yaml
app:
  port: 3300

db: 
  host: localhost
  port: 27017
  name: mydb

This is production.yaml file.

simple.js
const config = require('config');

let appPort = config.get('app.port');
console.log(`Application port: ${appPort}`);
...

The simple.js file is the same.

$ node simple.js
Application port: 3000
Database host: localhost
Database port: 27017
Database name: ydb
NODE_ENV: development

This is the output for the default environment. The configuration is loaded from default.yaml.

$ set NODE_ENV=production
$ node simple.js
Application port: 3300
Database host: localhost
Database port: 27017
Database name: mydb
NODE_ENV: production

We change the NODE_ENV variable with the set command. (Use export on Linux.) Now the configuration data is loaded from production.yaml file.

In this tutorial, we have used node-config package to create configuration files for our Node.js application.


Feathers configuration module for environments

https://bailer.gitbooks.io/feathersjs/content/configuration/readme.html

feathers-configuration allows you to load default and environment specific JSON and/or JS configuration files and environment variables and set them on your application. In a generated application the config/default.json and config/production.json files are set up with feathers-configuration automatically.

Here is what it does:

  • Given a NODE_CONFIG_DIR environment variable it will load a default.json in that path, the default here is ./config.
  • When the NODE_ENV is not development, also try to load <NODE_ENV>.json in that path and merge both configurations (with <NODE_ENV>.json taking precedence)
  • Go through each configuration value and sets it on the application (via app.set(name, value)).
    • If the value is a valid environment variable (e.v. NODE_ENV), use its value instead
    • If the value start with ./ or ../ turn it to an absolute path relative to the configuration file path
    • If the value starts with a \, do none of the above two



Feathers Examples



Query with custom limit set for returned items in list


{{base_url}}/m-countries/?show=yes&$limit=100


Feathers modules



Feathers Development Model


use VSCode

create the api service 

setup configs for environments 

run the api service for an environment



Nodejs Basics 

https://www.w3schools.com/nodejs/ref_modules.asp


Node.js CLI app with OAuth security

https://developer.okta.com/blog/2019/06/18/command-line-app-with-nodejs

node-cli-ex-oauth-developer.okta-Build a Command Line Application with Nodejs.pdf


Modules - builtin and custom 

https://www.w3schools.com/nodejs/nodejs_modules.asp


Create a module that returns the current date and time:

exports.myDateTime = function () {
  return Date();
};

Use the exports keyword to make properties and methods available outside the module file.

Save the code above in a file called "myfirstmodule.js

Include modules with require

var http = require('http');
var dt = require('./myfirstmodule');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write("The date and time are currently: " + dt.myDateTime());
  res.end();
}).listen(8080);

Http module to create a server

Need a header record for type 

Pass req, res variables to set request, get response

var http = require('http');
http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/html'});
  res.write(req.url);
  res.end();
}).listen(8080);


NPM package manager installed with Node.js

https://www.w3schools.com/nodejs/nodejs_npm.asp

NPM is a package manager for Node.js packages, or modules if you like.

www.npmjs.com hosts thousands of free packages to download and use.

The NPM program is installed on your computer when you install Node.js

A package in Node.js contains all the files you need for a module.

Modules are JavaScript libraries you can include in your project.

npm install mypackage

Events module

https://www.w3schools.com/nodejs/nodejs_events.asp

you can create-, fire-, and listen for- your own events.

Similar to Java beans where events are built-in with create event, addListener, fireEvent

Objects in Node.js can fire events, like the readStream object fires events when opening and closing a file:

Create eventEmitter

var events = require('events');
var eventEmitter = new events.EventEmitter();

Email module 

https://www.w3schools.com/nodejs/nodejs_email.asp


Potential Value Opportunities



Potential Challenges



Candidate Solutions




Step-by-step guide for Example



sample code block

sample code block
 



Recommended Next Steps