query.createEach.transform.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. var assert = require('assert');
  2. var _ = require('@sailshq/lodash');
  3. var Waterline = require('../../../lib/waterline');
  4. describe('Collection Query ::', function() {
  5. describe('.createEach()', function() {
  6. var modelDef = {
  7. identity: 'user',
  8. datastore: 'foo',
  9. primaryKey: 'id',
  10. fetchRecordsOnCreateEach: true,
  11. attributes: {
  12. id: {
  13. type: 'number'
  14. },
  15. name: {
  16. type: 'string',
  17. defaultsTo: 'Foo Bar',
  18. columnName: 'login'
  19. }
  20. }
  21. };
  22. it('should transform values before sending to adapter', function(done) {
  23. var waterline = new Waterline();
  24. waterline.registerModel(Waterline.Model.extend(_.extend({}, modelDef)));
  25. // Fixture Adapter Def
  26. var adapterDef = {
  27. createEach: function(con, query, cb) {
  28. assert(_.first(query.newRecords).login);
  29. var id = 0;
  30. query.newRecords = _.map(query.newRecords, function(newRecord) { newRecord.id = ++id; return newRecord; });
  31. return cb(null, query.newRecords);
  32. }
  33. };
  34. var connections = {
  35. 'foo': {
  36. adapter: 'foobar'
  37. }
  38. };
  39. waterline.initialize({ adapters: { foobar: adapterDef }, datastores: connections }, function(err, orm) {
  40. if (err) {
  41. return done(err);
  42. }
  43. orm.collections.user.createEach([{ name: 'foo' }], done);
  44. });
  45. });
  46. it('should transform values after receiving from adapter', function(done) {
  47. var waterline = new Waterline();
  48. waterline.registerModel(Waterline.Model.extend(_.extend({}, modelDef)));
  49. // Fixture Adapter Def
  50. var adapterDef = {
  51. createEach: function(con, query, cb) {
  52. var id = 0;
  53. query.newRecords = _.map(query.newRecords, function(newRecord) { newRecord.id = ++id; return newRecord; });
  54. return cb(null, query.newRecords);
  55. }
  56. };
  57. var connections = {
  58. 'foo': {
  59. adapter: 'foobar'
  60. }
  61. };
  62. waterline.initialize({ adapters: { foobar: adapterDef }, datastores: connections }, function(err, orm) {
  63. if (err) {
  64. return done(err);
  65. }
  66. orm.collections.user.createEach([{ name: 'foo' }], function(err, values) {
  67. if (err) {
  68. return done(err);
  69. }
  70. assert(values[0].name);
  71. assert(!values[0].login);
  72. return done();
  73. });
  74. });
  75. });
  76. });
  77. });