UpdateAndFetchOperation.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. const DelegateOperation = require('./DelegateOperation');
  2. const UpdateOperation = require('./UpdateOperation');
  3. const { afterReturn } = require('../../utils/promiseUtils');
  4. class UpdateAndFetchOperation extends DelegateOperation {
  5. constructor(name, opt) {
  6. super(name, opt);
  7. if (!this.delegate.is(UpdateOperation)) {
  8. throw new Error('Invalid delegate');
  9. }
  10. this.id = null;
  11. this.skipIdWhere = false;
  12. }
  13. get model() {
  14. return this.delegate.model;
  15. }
  16. onAdd(builder, args) {
  17. this.id = args[0];
  18. return this.delegate.onAdd(builder, args.slice(1));
  19. }
  20. onBuild(builder) {
  21. super.onBuild(builder);
  22. if (!this.skipIdWhere) {
  23. const idColumn = builder.fullIdColumnFor(builder.modelClass());
  24. const id = this.id;
  25. builder.whereComposite(idColumn, id);
  26. }
  27. }
  28. onAfter2(builder, numUpdated) {
  29. if (numUpdated == 0) {
  30. // If nothing was updated, we should fetch nothing.
  31. return afterReturn(super.onAfter2(builder, numUpdated), undefined);
  32. }
  33. return builder
  34. .modelClass()
  35. .query()
  36. .childQueryOf(builder)
  37. .whereComposite(builder.fullIdColumnFor(builder.modelClass()), this.id)
  38. .castTo(builder.resultModelClass())
  39. .first()
  40. .then(fetched => {
  41. let retVal = undefined;
  42. if (fetched) {
  43. this.model.$set(fetched);
  44. retVal = this.model;
  45. }
  46. return afterReturn(super.onAfter2(builder, numUpdated), retVal);
  47. });
  48. }
  49. }
  50. module.exports = UpdateAndFetchOperation;