File size: 1,689 Bytes
cf0f72e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
'use strict';

var buildActions = require('build-actions');

/**
 * Creates or update a customer.
 *
 * @public
 * @param {Object} data Customer object
 * @param {next} Callback
 */
function worker(data, next) {
  var email = encodeURIComponent('email="' + data.email + '"')
    , client = this.client
    , loader = this;

  //
  // For the same of simplicity assume that the `email` field is good enough
  // to uniquely match a customer.
  // @todo This is actually not a good idea because the email can be updated.
  //
  client.get('/customers?where=' + email, function get(err, res, body) {
    if (err || res.statusCode !== 200) {
      return next(err || new Error(body.message));
    }

    var customer = body.results[0];

    if (!customer) {
      //
      // If a match has not been found, create the customer.
      // @todo Pick only the valid properties from `data`.
      //
      client.post('/customers', data, function post(err, res, body) {
        if (err || res.statusCode !== 201) {
          return next(err || new Error(body.message));
        }

        loader.created++;
        next();
      });

      return;
    }

    var actions = buildActions(customer, data);

    //
    // Bail out if there are no changes, otherwise update the customer.
    //
    if (!actions.length) return next();

    client.post('/customers/' + customer.id, {
      version: customer.version,
      actions: actions
    }, function post(err, res, body) {
      if (err || res.statusCode !== 200) {
        return next(err || new Error(body.message));
      }

      loader.updated++;
      next();
    });
  });
}

//
// Expose the `worker` function.
//
module.exports = worker;