Welcome Guest, Not a member yet? Register   Sign In
nodejs tips and tricks
#21

A week with hapijs (thoughts)

After spending a week with hapijs I just want to tell you my initial thoughts.

Firstly, this is difficult, you will be scratching your head most of the time. The syntax is confusing, something you can end with a semi colon sometimes you don't. This depends on the library you are using. Second, even with hapijs you need a lot of middleware. You need a plugin to serve files and images, there is no official server side session management, it is a repo created by someone. Yes it has client side cookie management but remember how happy we were when codeigniter finally added native PHP sessions to the framework!

Third, you'll have a lot of trouble following video tutorials most are written in earlier versions of hapi, so version 17 is completely different, the Joi, form validation for example, doesn't echo out the actual error messages, it just shows you a pass or fail message.

Connecting to a mysql database is easy enough if you use the mysql npm module, you can even use prepared statements and create a persistent connection. You can load other files on the fly and access their methods with.

https://www.sitepoint.com/understanding-...s-node-js/

For hashing passwords you have to use npm bcrypt, but on the mac that doesn't work so you have to use bcyrptjs, which is a subtlety that took ages to figure out.

Rendering views is fairly easy if you are using handlebars. To access POST data you need to call the data.payload method.

It becomes a bit tedious to start and stop the server to debug the program, so I recommend using node supervisor which allows you to change code without restarting the server.

https://github.com/petruisfan/node-supervisor

I did briefly take a look at full MVC frameworks like sails, but they are huge and confusing. Overall, it was a very frustrating experience. But I feel now I can create a simple framework that does most of the things codeigniter does albeit without it all being nicely wrapped within helpers functions etc.

I'm glad I did try this as it is always good to know as I think bigger companies will be looking for these skillsets, especially for multi-threading applications.
Practical guide to IgnitedCMS - Book coming soon, www.ignitedcms.com
Reply
#22

Wow I just spent the entire day trying to decipher form validation using Joi, as per usual the documentation was difficult to decipher. There were no example using forms and routes that were easy. In the end I got something like this.

Code:
const Joi = require('joi');
    const userSchema = {
      name: Joi.number(),
      author:Joi.string()
      
    }


    server.route({
    method: 'POST',
    path: '/hello/{name}',
    handler: function (request, h) {

        //get the $_POST of name

        // const payload = request.payload
        // return payload.name

         const result = Joi.validate({ name: '1',author:''}, userSchema)

         var str = result.error;
         console.log(str)

         if(str === null)
         {
            return ('Success')
         }
         else
         {
            return(str.message)
         }
         //do something with error

    }

Next on the list, is probably file uploading using multr, I will leave sessions to last.

I am using hapi-auto-route to auto load routes from another script

Code:
{
  "name": "nodejs",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcryptjs": "^2.4.3",
    "handlebars": "^4.0.12",
    "hapi": "^17.5.4",
    "hapi-auth-basic": "^5.0.0",
    "hapi-auto-route": "^2.0.3",
    "inert": "^5.1.0",
    "joi": "^13.6.0",
    "vision": "^5.4.0"
  }
}
Practical guide to IgnitedCMS - Book coming soon, www.ignitedcms.com
Reply
#23

(This post was last modified: 09-20-2018, 09:26 AM by ignitedcms.)

Mysql findings

Holy crap guys, you don't know how complicated it is to return a full mysql result string to a view file!

Because nodejs / hapijs is asynchronous (meaning it does not necessarily execute in order e.g mysql fetches and file reading) you can't easily return the result of a mysql query save it into a variable and dump it to a view. This is a complete mind f*** for anyone not used to asynchronous coding. I will investigate this further. Woah this is difficult.

I believe the answer is to use async and await. . . Arrrgh.
Practical guide to IgnitedCMS - Book coming soon, www.ignitedcms.com
Reply
#24

(09-20-2018, 09:25 AM)ignitedcms Wrote: Mysql findings

Holy crap guys, you don't know how complicated it is to return a full mysql result string to a view file!

Because nodejs / hapijs is asynchronous (meaning it does not necessarily execute in order e.g mysql fetches and file reading) you can't easily return the result of a mysql query save it into a variable and dump it to a view. This is a complete mind f*** for anyone not used to asynchronous coding. I will investigate this further. Woah this is difficult.

I believe the answer is to use async and await. . . Arrrgh.

Or use promises and Promise.all()
Reply
#25

(09-20-2018, 10:26 AM)skunkbad Wrote:
(09-20-2018, 09:25 AM)ignitedcms Wrote: Mysql findings

Holy crap guys, you don't know how complicated it is to return a full mysql result string to a view file!

Because nodejs / hapijs is asynchronous (meaning it does not necessarily execute in order e.g mysql fetches and file reading) you can't easily return the result of a mysql query save it into a variable and dump it to a view. This is a complete mind f*** for anyone not used to asynchronous coding. I will investigate this further. Woah this is difficult.

I believe the answer is to use async and await. . . Arrrgh.

Or use promises and Promise.all()

Interesting, I came across these two and it looks good, I'm going to run a few tests today.

https://github.com/Will-I4M/node-mysql-libmysqlclient

https://www.npmjs.com/package/promise-mysql

I'll let you know my findings.
Practical guide to IgnitedCMS - Book coming soon, www.ignitedcms.com
Reply
#26

Ok guys the promises seemed to have worked, just need to pass it into the view

Code:
var mysql = require('promise-mysql');

           let tmp =

            mysql.createConnection({
                host: 'localhost',
                user: 'root',
                password: 'root',
                database: 'databasename',
                port: '8889'
            }).then(function(conn){
                var result = conn.query('select `permission` from IGS_permissions');
                conn.end();
                return result;
            }).then(function(rows){
                
                console.log(rows);
                tmp = rows
                return tmp
            });


            return tmp

Which dumps out:

Code:
[{"permission":"email"},{"permission":"permissions"},{"permission":"profile"},{"permission":"users"},{"permission":"menu"},{"permission":"database"},{"permission":"field_builder"},{"permission":"sections"},{"permission":"entries"},{"permission":"asset_lib"},{"permission":"site_settings"},{"permission":"plugins"}]
Practical guide to IgnitedCMS - Book coming soon, www.ignitedcms.com
Reply
#27

Guys I'm getting nowhere with hapi 17, it is just too confusing to send a database query back to the view, there's not enough examples, which is a shame because I was quite some way in building a mini framework. So I'm switching to express.js.

I really think making asynchronous mysql queries makes writing business logic so much harder, I guess this is why so many example do the processing inside the function and don't pass anything back.

Well that was interesting.
Practical guide to IgnitedCMS - Book coming soon, www.ignitedcms.com
Reply
#28

Guys just a quick update, after a few tests, it seems express is a lot easier! Way easier. Just got to check it with mysql and I should be good to go!
Practical guide to IgnitedCMS - Book coming soon, www.ignitedcms.com
Reply
#29

(This post was last modified: 09-21-2018, 11:28 PM by ignitedcms.)

@skunkbad dear lord! I looked over a reactjs tutorial compared to vuejs and the difference was huge, the syntax for vuejs is less verbose easier to figure out etc. It's just a shame reactjs has the bigger market share. Have you tried vuejs? It is a pure joy to work with.
Practical guide to IgnitedCMS - Book coming soon, www.ignitedcms.com
Reply
#30

(09-21-2018, 06:37 PM)ignitedcms Wrote: @skunkbad dear lord! I looked over a reactjs tutorial compared to vuejs and the difference was huge, the syntax for vuejs is less verbose easier to figure out etc. It's just a shame reactjs has the bigger market share. Have you tried vuejs? It is a pure job to work with.

I’ve tried both, and initially preferred vuejs. If I can only pick one, I’ve got to go with the money maker.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB