From db8b8742c4fc22b07090764245a196f460330f38 Mon Sep 17 00:00:00 2001 From: Robin Ward Date: Mon, 14 Sep 2020 14:29:03 -0400 Subject: [PATCH] DEV: Add support for `api-initializers` to reduce boilerplate. You can now create a file in your plugin/theme in the `api-initializers` directory which has a simpler template than previous initializers. Example: ``` // api-initializers/my-plugin.js import { apiInitializer } from "discourse/lib/api"; export default apiInitializer("0.8", api => { console.log("hello world from api initializer!"); }); ``` --- app/assets/javascripts/discourse/app/app.js | 2 +- .../javascripts/discourse/app/lib/api.js | 18 ++++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 app/assets/javascripts/discourse/app/lib/api.js diff --git a/app/assets/javascripts/discourse/app/app.js b/app/assets/javascripts/discourse/app/app.js index 06e5064e3e2..2dd26a5d0ff 100644 --- a/app/assets/javascripts/discourse/app/app.js +++ b/app/assets/javascripts/discourse/app/app.js @@ -154,7 +154,7 @@ const Discourse = Application.extend({ Object.keys(requirejs._eak_seen).forEach(key => { if (/\/pre\-initializers\//.test(key)) { this.initializer(this._prepareInitializer(key)); - } else if (/\/initializers\//.test(key)) { + } else if (/\/(api\-)?initializers\//.test(key)) { this.instanceInitializer(this._prepareInitializer(key)); } }); diff --git a/app/assets/javascripts/discourse/app/lib/api.js b/app/assets/javascripts/discourse/app/lib/api.js new file mode 100644 index 00000000000..51a933f67ad --- /dev/null +++ b/app/assets/javascripts/discourse/app/lib/api.js @@ -0,0 +1,18 @@ +import { withPluginApi } from "discourse/lib/plugin-api"; + +/** + * apiInitializer(version, apiCodeCallback, opts) + * + * An API to simplify the creation of initializers for plugins/themes by removing + * some of the boilerplate. + */ +let _apiInitializerId = 0; +export function apiInitializer(version, cb, opts) { + return { + name: `api-initializer${_apiInitializerId++}`, + after: "inject-objects", + initialize() { + return withPluginApi(version, cb, opts); + }, + }; +}