jeudi 7 septembre 2017

How to return randomized data on get request in Node ExpressJS?

I've set up a route in express and I want to return a randomized string based on given characters.

api/practice.js

    const express = require('express');

    const router = express.Router();

    function randomChar(charArray) {
      //returns random character based of character array
      return charArray[Math.floor(Math.random() * (charArray.length))];
    }

    function exerciseGenerator(charArray) {
    //returns randomized string
      let string = '';
      let i;

      for (i = 0; string.length < 100; i += 1) {
        string += randomChar(charArray);
        // insert space at random
        if (string.slice(-2) !== ' ' && Math.random() < 0.3 && string.length < 100) {
          string += ' ';
        }
      }
      return string;
    }

    const exercises = {
      items: [
        {
          id: 0,
          name: 'title 0',
          string: ['d','f'],
        },
        {
          id: 1,
          name: 'title 1',
          string: ['f', 'j'],
        },

      ],
    };

    // specific routing with parameters
    router.get('/:id', (req, res) => {
      let exercise = exercises.items[req.params.id];
      if (exercise.string.constructor === Array) {  
        exercise.string = exerciseGenerator(exercise.string);
      }
      res.json({ api: exercise });
    });

    module.exports = router;

So making a request to localhost:3000/api/practice/0 returns this for example:

"df d f dfdf f d d f d f d dd d ddff f"

Now this is how it should work, but there's one caveat: the response is giving the same randomized string on subsequent calls. Only when I restart the server I get a new randomized string. Obviously, how I think it works, is not how it really works.

Why is this happening and how do I overcome this problem?




Aucun commentaire:

Enregistrer un commentaire