Unit 2, Lesson 4

$\textbf{Functions in Node.JS}$
$\text{Written by:} $
$\text{Dev Singh, Class of 2020}$
$\text{Last Revised: March 2020}$

Normal function structure

In [1]:
function sayGenericHello() {
    console.log("Hello!")
}

Note how the above function has no parameters

In [2]:
function sayHello(nameToGreet) {
    let memer = true
    console.log("Hello, " + nameToGreet)
    console.log(memer)
}

Note how the above function takes one parameter, and it's following behavior when it does not recieve that arguement.

In [3]:
sayHello()
Hello, undefined
true
In [4]:
sayHello("Stoodents")
Hello, Stoodents
true

Guiding Questions

How would I implement some sort of system where if the name is undefined, to replace it with "Unknown Person"?

What do you think would happen if I were to try to console.log() the value of memer outside of the function?

What was returned by sayHello(), if anything? How do you think I could define a return?

Anonymous Functions

In [5]:
let sayHello2 = function (nameToGreet) {
    console.log("Hello, " + nameToGreet)
}
In [6]:
sayHello2("Memer")
Hello, Memer

Arrow functions

As you may see, the syntax of defining functions in JS is somewhat ugly. A different syntax, arrow functions, have some cleaner syntax. Arrow functions were introduced in ECMAScript 6 and allow you to write cleaner code.

In [7]:
let sayHello3 = (nameToGreet) => { // the `let` is not technically neccessary.
    console.log("Hello, " + nameToGreet)
}
let sayHelloGeneric1 = () => { // the `let` is not technically neccessary.
    console.log("Hello!")
}
In [8]:
sayHello3("Person")
Hello, Person
In [9]:
sayHelloGeneric1()
Hello!

Topics we will go over in session

  • async/await and the concept of promises
  • Callbacks

Code snippet for analysis

(Yes, I stole this from my Robotics code)

In [ ]:
let express = require("express")
let bodyParser = require("body-parser")
let dbHandler = require('./dbHandler.js')
let auth = require('./authHandler.js')
let expressMongoDb = require('express-mongo-db');
const port = process.env.PORT || 8190;

app = express()
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
let options = {
    keepAlive: 1, connectTimeoutMS: 30000
};
app.use(expressMongoDb('mongodb+srv://api-user-new:titanscout2022@2022-scouting-4vfuu.mongodb.net/test?retryWrites=true&w=majority', options))

/**
 * POST route "/api/submitMatchData"
 * Allows the application to submit data to the API, with some key data seperated within the JSON and the rest submitted as arbirtary structures within the data key.
 * @param token in form of header with title 'token' and value of JWT provided by Google OAuth
 * @param competition_id is the identifier for the competition: e.g. "2020ilch".
 * @param match_number is the number of the match scouted: e.g. "1".
 * @param team_scouted is the team that was being scouted: e.g. "3061".
 * @param data is the arbritrary other data that needs to be recorded for the match.
 * @returns back to the client resobj (success boolean, competition id, and match number) and HTTP Status Code 200 OK.
 */
app.post("/api/submitMatchData", auth.checkAuth, async (req, res) => {
    let val;
    const scouter = {name: String(res.locals.name), id: String(res.locals.id)}
    const competition_id = String(req.body.competition_id)
    const match_number = parseInt(req.body.match_number)
    const team_scouted = parseInt(req.body.team_scouted)
    const data = req.body.data
    try{
        val = await dbHandler.submitMatchData(req.db, scouter, competition_id, match_number, team_scouted, data).catch(e => {console.error(e); val.err_occur = true;})
    } catch (err) {
        console.error(err)
        val.err_occur = true;
    }
    if (val.err_occur == false) {
        resobj = {
            "success": true,
            "competition": competition_id,
            "match_number" : match_number,
        }
    } else {
        resobj = {
            "success": false,
            "reasons": val.err_reasons,
        }
    }
    res.json(resobj)
})