Lab4 ‐ Asynchronous Programming and Express - isel-leic-pi/IPW-2627i-LEIRT31D GitHub Wiki

Asynchronous Programming – Promises

1. Using crypto.randomBytes with Promises

Create a function randomBytesPromise(size) that wraps the Node.js crypto.randomBytes function in a Promise by explicitly using the Promise constructor.

  • The function should return a Promise that resolves with the generated bytes as a Buffer.
  • If an error occurs, the Promise should be rejected.

Example of Use randomBytes with callback:

import { randomBytes } from 'node:crypto';

randomBytes(16, (err, buffer) => {
    if (err) {
        console.log('Erro:', err);
        return;
    }

    console.log('Random bytes:', buffer.toString('hex'));
});

Example of Use:

randomBytesPromise(16)
  .then(buffer => {
    console.log('Random bytes:', buffer.toString('hex'));
  })
  .catch(err => {
    console.error('Error:', err);
  });

2. General promisifyFunction

Create a general function promisifyFunction(fn, ...args) that converts any Node.js callback-style function (err, result) into a Promise by explicitly using the Promise constructor.

Example of Use:

promisifyFunction(crypto.randomBytes, 16)
  .then(buffer => {
    console.log('Random bytes:', buffer.toString('hex'));
  })
  .catch(err => {
    console.error('Error:', err);
  });

Web API with Express

Student Management API

Using the Express library in Node.js, create a Web API to manage a collection of students stored in memory (using an array). Each student must have the following properties:

  • id – automatically generated unique identifier
  • name – string representing the student's name
  • number – numeric student number

Requirements

The API must support the following operations:

HTTP Method Path Template Description
GET /students Returns all students. Supports a query string parameter limit to restrict the number of students returned.
GET /students/:id Returns the student with the specified id.
POST /students Creates a new student. Requires a JSON body with name and number.

Additional Notes

  • All responses must be in JSON format.
  • The API should handle errors properly, returning meaningful error messages (e.g. "Student not found", "Invalid data").
  • The server must run on port 3000.
  • Students must be stored in memory (not in a database), using an array.

Example Request Body for Creating a Student

POST /students

{
  "name": "Ana Silva",
  "number": 12345
}

Example Response Body

{
  "id": 1,
  "name": "Ana Silva",
  "number": 12345
}