module.exports = function()

in source/services/systems/lib/refresh-system.js [98:172]


module.exports = function(event, context) {
    const tag = `${lib}:`;
    // Event:
    // {
    //     "cmd": "refreshSystem",
    //     "systemId": "id"
    // }

    // First get the system
    let _system;
    return documentClient
        .get({
            TableName: process.env.TABLE_SYSTEMS,
            Key: {
                id: event.id
            }
        })
        .promise()
        .then(system => {
            _system = system.Item;

            if (!_system) {
                throw 'System does not exist.';
            } else {
                console.log(tag, 'Found system');
                return documentClient
                    .get({
                        TableName: process.env.TABLE_SYSTEM_BLUEPRINTS,
                        Key: {
                            id: _system.systemBlueprintId
                        }
                    })
                    .promise();
            }
        })
        .then(systemBlueprint => {
            _systemBlueprint = systemBlueprint.Item;

            if (!_systemBlueprint) {
                throw 'SystemBlueprint ' + _system.systemBlueprintId + ' does not exist.';
            } else {
                if (
                    !_systemBlueprint.spec.hasOwnProperty('Devices') &&
                    _system.deviceIds.length !== _systemBlueprint.spec.Devices.length
                ) {
                    // throw 'System has inconsistent deviceIds and devices length in spec';
                    return [];
                } else {
                    return Promise.all(
                        _system.deviceIds.map(thingId => {
                            return documentClient
                                .get({
                                    TableName: process.env.TABLE_DEVICES,
                                    Key: {
                                        thingId: thingId
                                    }
                                })
                                .promise()
                                .then(device => {
                                    device = device.Item;
                                    if (!device) {
                                        throw 'Device for thingId ' + thingId + ' does not exist anymore!';
                                    }
                                    return device;
                                });
                        })
                    );
                }
            }
        })
        .then(devices => {
            console.log(tag, 'end:', devices);
            return processDeviceList(_systemBlueprint.spec.Devices, devices);
        });
};