1
\$\begingroup\$
  register(name, version, ip, port) {
    this.cleanup();
    const key = name + version + ip + port;

    if (!this.services[key]) {
      this.services[key] = {};
      this.services[key].timestamp = Math.floor(new Date() / 1000);
      this.services[key].ip = ip;
      this.services[key].port = port;
      this.services[key].name = name;
      this.services[key].version = version;
      this.log.debug(`Added services ${name}, version ${version} at ${ip}:${port}`);
      return key;
    }
    this.services[key].timestamp = Math.floor(new Date() / 1000);
    this.log.debug(`Updated services ${name}, version ${version} at ${ip}:${port}`);
    return key;
  }

I thought the code looked kinda amateurish. I am not sure if I am imagining things. Isn't there a better way to assign values, also what about how the key is made, shouldn't we use a random string generator or at least encode it after appending the values? What's the best practice?

https://github.com/bluebrid/base-knowledge/blob/317bcdacd3a3806a6f98f05a7660dc97c506e8fb/javascript/advance/microservices/demo.1/service-registry/server/lib/ServiceRegistry.js

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

The code is pretty clear, I wouldn't call amateurish. Some cleanup could be done, though.

Avoid duplication

The timestamp code is duplicated, you could create a function for it:

const getTimestamp = () => {
    return Math.floor(new Date() / 1000)
}

You'll see below I refactored the register method to only set the timestamp once, but this still holds as a general recommendation: don't repeat the same code.

String building

Personally I prefer to use the backtick to build strings from variables:

const alpha = 'alpha';
const bravo = 'bravo';
const key = `${alpha}${bravo}`;

Assignment shorthand

ES6 provides a shorthand for object property assignment. If a key has the same name as a variable passed in as a property, you only need to specify the key name. Your service object is a perfect candidate for this:

register(name, version, ip, port) {
    this.cleanup();

    const key = `${name}${version}${ip}${port}`;
    let operation = 'Updated'

    if (!this.services[key]) {
        operation = 'Added'
        this.services[key] = {
            name, version, ip, port
        };
    }
    this.services[key].timestamp = Math.floor(new Date() / 1000);

    this.log.debug(`${operation} services ${name}, version ${version} at ${ip}:${port}`);
    return key;
}
    
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.