Saturday, 29 April 2017

Node Singleton Use

The author of this article uses singletons for the service layer in this example Node api:

https://html5hive.org/how-to-create-rest-api-with-node-js-and-express/

He states, "We only want there to ever be one instance of our player service, so instead of exporting the class itself, we’ll export a new instance of it. Module files in node are only ever executed once, so this effectively gives us a singleton."

'use strict';

var uuid = require('node-uuid');

class PlayersService {
    constructor() {
        this.players = [];
    }

    getPlayers() {
        return this.players;
    }

    getSinglePlayer(playerId) {
        var player = this.players.filter(p => p.id === playerId)[0];

        return player || null;
    }

    addPlayer(info) {
        // prevent a bit of bad/duplicate data
        if (!info || this.players.filter(p => (p.firstName === info.firstName && p.lastName === info.lastName)).length > 0) {
            return false;
        }

        info.id = uuid.v4();

        this.players.push(info);
        return true;
    }

    updatePlayer(playerId, info) {
        var player = this.getSinglePlayer(playerId);
        if (player) {
            player.firstName = info.firstName ? info.firstName : player.firstName;
            player.lastName = info.lastName ? info.lastName : player.lastName;
            player.displayName = info.displayName ? info.displayName : player.displayName;

            return true;
        }
        return false;
    }
}

module.exports = new PlayersService();

Which seems reasonable since the function of these services is to provide the same implementation for the controllers that use them.

However, in this post:

On Design Patterns: When to use the Singleton?

the poster asks for a legitimate use case for singletons other than a Logger class. Several people responded to his question by saying that singletons should never be used.

But isn't the use of singletons for services like the one I've copied here a legitimate use case and a best practice so that you are not creating multiple instances that provide the same implementation? Thanks.



via lance-p

No comments:

Post a Comment