From 7053ccd8ec33b9cc51674200e54b67c0ed1d34a8 Mon Sep 17 00:00:00 2001 From: Tony Alves Date: Thu, 25 Jan 2018 08:55:13 -0800 Subject: [PATCH] Register Internal and Custom backend API's (#1011) * allow backend register * handle multiple backends, including internal --- src/backends/backend.js | 22 +++++++++++++--------- src/lib/registry.js | 23 +++++++++++++++++++++++ 2 files changed, 36 insertions(+), 9 deletions(-) diff --git a/src/backends/backend.js b/src/backends/backend.js index 4f2771af..6be811f9 100644 --- a/src/backends/backend.js +++ b/src/backends/backend.js @@ -14,6 +14,15 @@ import { sanitizeSlug } from "Lib/urlHelper"; import TestRepoBackend from "./test-repo/implementation"; import GitHubBackend from "./github/implementation"; import GitGatewayBackend from "./git-gateway/implementation"; +import { registerBackend, getBackend } from 'Lib/registry'; + +/** + * Register internal backends + */ +registerBackend('git-gateway', GitGatewayBackend); +registerBackend('github', GitHubBackend); +registerBackend('test-repo', TestRepoBackend); + class LocalStorageAuthStore { storageKey = "netlify-cms-user"; @@ -339,15 +348,10 @@ export function resolveBackend(config) { const authStore = new LocalStorageAuthStore(); - switch (name) { - case "test-repo": - return new Backend(new TestRepoBackend(config), name, authStore); - case "github": - return new Backend(new GitHubBackend(config), name, authStore); - case "git-gateway": - return new Backend(new GitGatewayBackend(config), name, authStore); - default: - throw new Error(`Backend not found: ${ name }`); + if (!getBackend(name)) { + throw new Error(`Backend not found: ${ name }`); + } else { + return new Backend(getBackend(name).init(config), name, authStore); } } diff --git a/src/lib/registry.js b/src/lib/registry.js index 36f4e47d..b37cf733 100644 --- a/src/lib/registry.js +++ b/src/lib/registry.js @@ -5,6 +5,7 @@ import { newEditorPlugin } from 'EditorWidgets/Markdown/MarkdownControl/plugins' * Global Registry Object */ const registry = { + backends: { }, templates: {}, previewStyles: [], widgets: {}, @@ -24,6 +25,8 @@ export default { getEditorComponents, registerWidgetValueSerializer, getWidgetValueSerializer, + registerBackend, + getBackend, }; @@ -87,3 +90,23 @@ export function registerWidgetValueSerializer(widgetName, serializer) { export function getWidgetValueSerializer(widgetName) { return registry.widgetValueSerializers[widgetName]; }; + +/** + * Backend API + */ +export function registerBackend(name, BackendClass) { + if (!name || !BackendClass) { + console.error("Backend parameters invalid. example: CMS.registerBackend('myBackend', BackendClass)"); + } else if (registry.backends[name]) { + console.error(`Backend [${ name }] already registered. Please choose a different name.`); + } else { + registry.backends[name] = { + init: config => new BackendClass(config), + }; + } +} + +export function getBackend(name) { + return registry.backends[name]; +} +