raw-example.js 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. #!/usr/bin/env node
  2. /**
  3. * Module dependencies
  4. */
  5. var util = require('util');
  6. var _ = require('@sailshq/lodash');
  7. var SailsDiskAdapter = require('sails-disk');
  8. var Waterline = require('../../');
  9. /**
  10. * `raw-example.js`
  11. *
  12. * This is an example demonstrating how to use Waterline
  13. * from a vanilla Node.js script.
  14. *
  15. *
  16. * To run this example, do:
  17. * ```
  18. * node example/raw/raw-example
  19. * ```
  20. */
  21. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  22. //
  23. // NOTE: The `machine-as-script` package, like Sails, takes care of all this kind of
  24. // stuff automatically, including bootstrapping the ORM in the context of a Sails app.
  25. // (For deets, see https://npmjs.com/package/machine-as-script)
  26. //
  27. // But since we're doing this vanilla-style, we'll kick things off by calling a self-invoking
  28. // function here. This just lets us avoid repeating ourselves and gives us a level of control
  29. // over logging. See the two callbacks below in order to better understand how it works.
  30. //
  31. // > To read more general tips about managing flow and exposing customizable logic via
  32. // > self-invoking functions in Node.js apps/scripts, check out:
  33. // > https://www.npmjs.com/package/parley#flow-control
  34. //
  35. // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  36. (function (handleLog, done){
  37. // Set up Waterline.
  38. Waterline.start({
  39. adapters: {
  40. 'sails-disk': SailsDiskAdapter,
  41. // ...other Waterline-compatible adapters (e.g. 'sails-mysql') might go here
  42. },
  43. datastores: {
  44. default: {
  45. adapter: 'sails-disk'
  46. }
  47. },
  48. models: {
  49. user: {
  50. datastore: 'default',
  51. attributes: {
  52. id: { type: 'number', autoMigrations: { autoIncrement: true } },
  53. numChickens: { type: 'number' },
  54. pets: { collection: 'pet' }
  55. },
  56. primaryKey: 'id',
  57. schema: true
  58. },
  59. pet: {
  60. datastore: 'default',
  61. attributes: {
  62. id: { type: 'number', autoMigrations: { autoIncrement: true } },
  63. name: { type: 'string' }
  64. },
  65. primaryKey: 'id',
  66. schema: true
  67. }
  68. }
  69. }, function whenWaterlineIsReady (err, orm) {
  70. if (err) {
  71. return done(new Error('Could not start up Waterline ORM: '+err.stack));
  72. }//--•
  73. // Now kick off another self-invoking function.
  74. // (Once again, this is just to avoid repeating ourselves.)
  75. (function (proceed){
  76. handleLog();
  77. handleLog();
  78. handleLog('--');
  79. handleLog('Waterline ORM is started and ready.');
  80. // Get access to models:
  81. var Pet = Waterline.getModel('pet', orm);
  82. var User = Waterline.getModel('user', orm);
  83. handleLog();
  84. handleLog('(this is where you could write come code)');
  85. // ...for example, like this:
  86. handleLog(
  87. '\n'+
  88. '\n'+
  89. '==========================================================================\n'+
  90. '• EXAMPLE: Calling some model methods: •\n'+
  91. '==========================================================================\n'
  92. );
  93. var PET_NAMES = ['Carrie', 'Samantha', 'Charlotte', 'Miranda', 'Mr. Big'];
  94. Pet.createEach([
  95. { name: _.random(PET_NAMES) },
  96. { name: _.random(PET_NAMES) }
  97. ])
  98. .meta({fetch: true})
  99. .exec(function (err, pets) {
  100. if (err) { return proceed(new Error('Failed to create new pets: '+err.stack)); }
  101. User.create({
  102. numChickens: pets.length,
  103. pets: _.pluck(pets, 'id')
  104. })
  105. .exec(function (err) {
  106. if (err) { return proceed(new Error('Failed to create new user: '+err.stack)); }
  107. User.stream()
  108. .populate('pets')
  109. .eachRecord(function eachRecord(user, next){
  110. handleLog('Streamed record:',util.inspect(user,{depth: null}));
  111. return next();
  112. })
  113. .exec(function afterwards(err) {
  114. if (err) { return proceed(new Error('Unexpected error occurred while streaming users:',err.stack)); }
  115. return proceed();
  116. });//</ User.stream().exec() >
  117. });//</ User.create().exec() >
  118. });//</ Pet.createEach().exec() >
  119. })(function (err){
  120. if (err) {
  121. Waterline.stop(orm, function(secondaryErr) {
  122. if (secondaryErr) {
  123. handleLog();
  124. handleLog('An error occurred, and then, when trying to shut down the ORM gracefully, THAT failed too!');
  125. handleLog('More on the original error in just a while.');
  126. handleLog('But first, here\'s the secondary error that was encountered while trying to shut down the ORM:\n', secondaryErr);
  127. handleLog('... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ');
  128. return done(err);
  129. }//-•
  130. return done(err);
  131. });//_∏_
  132. return;
  133. }//-•
  134. // IWMIH, everything went well.
  135. handleLog();
  136. handleLog('Done. (Stopping ORM...)');
  137. handleLog('... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ');
  138. Waterline.stop(orm, function(secondaryErr) {
  139. if (secondaryErr) {
  140. return done(new Error('Everything else went fine, but then when attempting to shut down the ORM gracefully, something went wrong! Details:'+secondaryErr.stack));
  141. }
  142. return done();
  143. });
  144. });//</ inner self-invoking function>
  145. });//</ Waterline.start() >
  146. })(
  147. function handleLog(){ console.log.apply(console, Array.prototype.slice.call(arguments)); },
  148. function whenFinishedAndORMHasBeenStopped(err){
  149. if (err) {
  150. console.log();
  151. console.log(err.stack);
  152. console.log();
  153. console.log(' ✘ Something went wrong.');
  154. console.log(' (see stack trace above)');
  155. console.log();
  156. return process.exit(1);
  157. }//-•
  158. console.log();
  159. console.log(' ✔ OK.');
  160. console.log();
  161. return process.exit(0);
  162. }
  163. );//</ outer self-invoking function>