Home > Back-end >  How to generate an id when adding an object in node.js
How to generate an id when adding an object in node.js

Time:03-31

I am trying to append an id to an object if it's the first and if there are others I want to add 1 to one that I am adding. I am using function that is called save and insider there is a writeFile and an appendFile method

class Contenedor {
    constructor (nombre){
        this.nombre= nombre
        this.count = 0
        this.product = []
    }

    save(obj) {

        

        if (this.count <= 1){
            fs.writeFile(`./${this.nombre}`, JSON.stringify(obj), 'utf-8', (err)=> {
                if (err) {
                    console.log("Error al crear archivo")
                } else {
                    this.product.map(x=>{
                        x['id'] = this.count;
                        this.count  
                    })
                    console.log("Archivo creado")
                }
            })

        } else {
            fs.appendFile(`./${this.nombre}`, JSON.stringify(obj), 'utf-8', (err)=> {
                if (err) {
                    console.log("Error al crear archivo")
                } else {
                    this.product.map(x=>{
                        x['id'] = this.count;
                        this.count  
                    })
                    console.log("Archivo agregado")
                }
            })
        }
    }
}

let archivos = new Contenedor('text.json')

archivos.save(
    [
        {
            title: 'Escuadra',
            price: 152.50,
            thumbnail: 'https://external-content.duckduckgo.com/iu/?u=https://www.seawhite.co.uk/imagecache/6d084f72-7747-4b0c-a432-095215a06d70_749x440.jpg&f=1&nofb=1'
        }
]

so I want to have an unique id for the objects. I'm using map() method.

Anyone knows how to do it?

so I want to have an unique id for the objects. I'm using map() method. And already try this.count

Anyone knows how to do it?

CodePudding user response:

const fs = require('fs');
class Contenedor {
    constructor(nombre) {
        this.nombre = nombre
        this.count = 0
        this.product = []
        this.writelock = false;
        fs.writeFileSync(`./${this.nombre}`, '[');
    }

    save(obj) {
        if (this.writelock) {
            console.log('waiting for a sec');
            setTimeout(() => this.save(obj), 1000);
        } else {
            console.log('started writing', this.count);
            this.writelock = true;
            obj['id'] = this.count;
            let toWrite = JSON.stringify(obj, null, 2);
            if (this.count > 0) toWrite = ', '   toWrite;
            fs.appendFile(`./${this.nombre}`, toWrite, 'utf-8', (err) => {
                if (err) {
                    console.log("Error al crear archivo")
                } else {
                    this.product.push(obj);
                    this.count  ;
                    console.log("Archivo agregado");
                }
                this.writelock = false;
            })
        }
    }

    done() {
        if (this.writelock) {
            console.log('waiting for a sec');
            setTimeout(() => this.done(), 1000);
        } else {
            this.writelock = true;
            fs.appendFileSync(`./${this.nombre}`, ']', 'utf-8', (err) => {
                if (err) {
                    console.log("Error al crear archivo")
                }
                this.writelock = false;
            })
        }
    }
}

let archivos = new Contenedor('text.json')

archivos.save(
        {
            title: 'Escuadra',
            price: 152.50,
            thumbnail: 'https://external-content.duckduckgo.com/iu/?u=https://www.seawhite.co.uk/imagecache/6d084f72-7747-4b0c-a432-095215a06d70_749x440.jpg&f=1&nofb=1'
        }
)
archivos.save(
        {
            title: 'Escuadra',
            price: 100.50,
            thumbnail: 'https://external-content.duckduckgo.com/iu/?u=https://www.seawhite.co.uk/imagecache/6d084f72-7747-4b0c-a432-095215a06d70_749x440.jpg&f=1&nofb=1'
        }
)
archivos.save(
        {
            title: 'Escuadra',
            price: 126.50,
            thumbnail: 'https://external-content.duckduckgo.com/iu/?u=https://www.seawhite.co.uk/imagecache/6d084f72-7747-4b0c-a432-095215a06d70_749x440.jpg&f=1&nofb=1'
        }
)

archivos.done();

Added a write-lock in case save is used multiple times. You can remove that if you are going to add everything in one save only. Added '[' at the start and ']' at end of the JSON file to have a valid JSON file.

CodePudding user response:

Instead of reinventing the wheel and complicating things, just go simple. Use an randomUUID() for you unique id:

const { randomUUID } = require('crypto');
myObject.id = randomUUID();
  • Related