From f73d8346c25a65d8543986aef25cfce70190d693 Mon Sep 17 00:00:00 2001 From: David Taylor Date: Wed, 6 Sep 2023 15:11:05 +0100 Subject: [PATCH] DEV: Improve RestModel injections workaround (#23435) We have a workaround so that currentUser/siteSettings/appEvents work properly on RestModel instances which are created without an owner. This is not ideal, but fixing this properly is not trivial. This commit improves the workaround to be more robust and support all service injections. --- .../javascripts/discourse/app/models/rest.js | 29 +++++++++---------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/app/assets/javascripts/discourse/app/models/rest.js b/app/assets/javascripts/discourse/app/models/rest.js index 3c5e3060071..d512f300d43 100644 --- a/app/assets/javascripts/discourse/app/models/rest.js +++ b/app/assets/javascripts/discourse/app/models/rest.js @@ -1,7 +1,8 @@ import EmberObject from "@ember/object"; import { Promise } from "rsvp"; import { equal } from "@ember/object/computed"; -import { getOwner } from "discourse-common/lib/get-owner"; +import { getOwner as getOwnerWithFallback } from "discourse-common/lib/get-owner"; +import { getOwner, setOwner } from "@ember/application"; import { warn } from "@ember/debug"; const RestModel = EmberObject.extend({ @@ -101,23 +102,19 @@ RestModel.reopenClass({ create(args) { args = args || {}; - let owner = getOwner(this); - - // Some Discourse code calls `model.create()` directly without going through the - // store. In that case the injections are not made, so we do them here. Eventually - // we should use the store for everything to fix this. - if (!args.store) { - args.store = owner.lookup("service:store"); - } - if (!args.siteSettings) { - args.siteSettings = owner.lookup("service:site-settings"); - } - if (!args.appEvents) { - args.appEvents = owner.lookup("service:app-events"); - } args.__munge = this.munge; - return this._super(this.munge(args, args.store)); + const createArgs = this.munge(args, args.store); + + // Some Discourse code calls `model.create()` directly without going through the + // store. In that case the owner is not set, and injections will fail. This workaround ensures + // the owner is always present. Eventually we should use the store for everything to fix this. + const receivedOwner = getOwner(createArgs); + if (!receivedOwner || receivedOwner.isDestroyed) { + setOwner(createArgs, getOwnerWithFallback()); + } + + return this._super(createArgs); }, });