From b6a01a8bdb6598f85216b3ee29506695083b060b Mon Sep 17 00:00:00 2001 From: Patrik Oldsberg Date: Sat, 12 Oct 2024 11:29:19 +0200 Subject: [PATCH 1/7] new "modern" plugin as base for the new backend plugin template Signed-off-by: Patrik Oldsberg --- plugins/modern-backend/.eslintrc.js | 1 + plugins/modern-backend/README.md | 14 +++ plugins/modern-backend/catalog-info.yaml | 9 ++ plugins/modern-backend/dev/index.ts | 74 ++++++++++++ plugins/modern-backend/package.json | 48 ++++++++ plugins/modern-backend/src/index.ts | 17 +++ plugins/modern-backend/src/plugin.test.ts | 101 ++++++++++++++++ plugins/modern-backend/src/plugin.ts | 57 +++++++++ plugins/modern-backend/src/router.test.ts | 83 +++++++++++++ plugins/modern-backend/src/router.ts | 67 ++++++++++ .../TodoListService/createTodoListService.ts | 114 ++++++++++++++++++ .../src/services/TodoListService/index.ts | 17 +++ .../src/services/TodoListService/types.ts | 43 +++++++ plugins/modern-backend/src/setupTests.ts | 17 +++ 14 files changed, 662 insertions(+) create mode 100644 plugins/modern-backend/.eslintrc.js create mode 100644 plugins/modern-backend/README.md create mode 100644 plugins/modern-backend/catalog-info.yaml create mode 100644 plugins/modern-backend/dev/index.ts create mode 100644 plugins/modern-backend/package.json create mode 100644 plugins/modern-backend/src/index.ts create mode 100644 plugins/modern-backend/src/plugin.test.ts create mode 100644 plugins/modern-backend/src/plugin.ts create mode 100644 plugins/modern-backend/src/router.test.ts create mode 100644 plugins/modern-backend/src/router.ts create mode 100644 plugins/modern-backend/src/services/TodoListService/createTodoListService.ts create mode 100644 plugins/modern-backend/src/services/TodoListService/index.ts create mode 100644 plugins/modern-backend/src/services/TodoListService/types.ts create mode 100644 plugins/modern-backend/src/setupTests.ts diff --git a/plugins/modern-backend/.eslintrc.js b/plugins/modern-backend/.eslintrc.js new file mode 100644 index 0000000000..e2a53a6ad2 --- /dev/null +++ b/plugins/modern-backend/.eslintrc.js @@ -0,0 +1 @@ +module.exports = require('@backstage/cli/config/eslint-factory')(__dirname); diff --git a/plugins/modern-backend/README.md b/plugins/modern-backend/README.md new file mode 100644 index 0000000000..929b0a189f --- /dev/null +++ b/plugins/modern-backend/README.md @@ -0,0 +1,14 @@ +# modern + +Welcome to the modern backend plugin! + +_This plugin was created through the Backstage CLI_ + +## Getting started + +Your plugin has been added to the example app in this repository, meaning you'll be able to access it by running `yarn +start` in the root directory, and then navigating to [/modern/health](http://localhost:7007/api/modern/health). + +You can also serve the plugin in isolation by running `yarn start` in the plugin directory. +This method of serving the plugin provides quicker iteration speed and a faster startup and hot reloads. +It is only meant for local development, and the setup for it can be found inside the [/dev](./dev) directory. diff --git a/plugins/modern-backend/catalog-info.yaml b/plugins/modern-backend/catalog-info.yaml new file mode 100644 index 0000000000..fd4b9dc0ba --- /dev/null +++ b/plugins/modern-backend/catalog-info.yaml @@ -0,0 +1,9 @@ +apiVersion: backstage.io/v1alpha1 +kind: Component +metadata: + name: backstage-plugin-modern-backend + title: '@backstage/plugin-modern-backend' +spec: + lifecycle: experimental + type: backstage-backend-plugin + owner: maintainers diff --git a/plugins/modern-backend/dev/index.ts b/plugins/modern-backend/dev/index.ts new file mode 100644 index 0000000000..393f979bed --- /dev/null +++ b/plugins/modern-backend/dev/index.ts @@ -0,0 +1,74 @@ +/* + * Copyright 2024 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +import { createBackend } from '@backstage/backend-defaults'; +import { mockServices } from '@backstage/backend-test-utils'; +import { catalogServiceMock } from '@backstage/plugin-catalog-node/testUtils'; + +// TEMPLATE NOTE: +// This is the development setup for your plugin that wires up a +// minimal backend that can use both real and mocked plugins and services. +// +// Start up the backend by running `yarn start` in the package directory. +// It's it's up and running, try out the following requests: +// +// Create a new todo item: +// +// curl http://localhost:7007/api/modern/todos -H 'Content-Type: application/json' -d '{"title": "My Todo"}' +// +// List TODOs: +// +// curl http://localhost:7007/api/modern/todos +// +// Explicitly make an unauthenticated request, or with service auth: +// +// curl http://localhost:7007/api/modern/todos -H 'Authorization: Bearer mock-none-token' +// curl http://localhost:7007/api/modern/todos -H 'Authorization: Bearer mock-service-token' + +const backend = createBackend(); + +// TEMPLATE NOTE: +// Mocking the auth and httpAuth service allows you to call your plugin API without +// having to authenticate. +// +// If you want to use real auth, you can install the following instead: +// backend.add(import('@backstage/plugin-auth-backend')); +// backend.add(import('@backstage/plugin-auth-backend-module-guest-provider')); +backend.add(mockServices.auth.factory()); +backend.add(mockServices.httpAuth.factory()); + +// TEMPLATE NOTE: +// Rather than using a real catalog you can use a mock with a fixed set of entities. +backend.add( + catalogServiceMock.factory({ + entities: [ + { + apiVersion: 'backstage.io/v1alpha1', + kind: 'Component', + metadata: { + name: 'sample', + title: 'Sample Component', + }, + spec: { + type: 'service', + }, + }, + ], + }), +); + +backend.add(import('../src')); + +backend.start(); diff --git a/plugins/modern-backend/package.json b/plugins/modern-backend/package.json new file mode 100644 index 0000000000..def56e6ce3 --- /dev/null +++ b/plugins/modern-backend/package.json @@ -0,0 +1,48 @@ +{ + "name": "@backstage/plugin-modern-backend", + "version": "0.0.0", + "backstage": { + "role": "backend-plugin" + }, + "publishConfig": { + "access": "public", + "main": "dist/index.cjs.js", + "types": "dist/index.d.ts" + }, + "license": "Apache-2.0", + "main": "src/index.ts", + "types": "src/index.ts", + "files": [ + "dist" + ], + "scripts": { + "build": "backstage-cli package build", + "clean": "backstage-cli package clean", + "lint": "backstage-cli package lint", + "prepack": "backstage-cli package prepack", + "postpack": "backstage-cli package postpack", + "start": "backstage-cli package start", + "test": "backstage-cli package test" + }, + "dependencies": { + "@backstage/backend-defaults": "workspace:^", + "@backstage/backend-plugin-api": "workspace:^", + "@backstage/catalog-client": "workspace:^", + "@backstage/errors": "workspace:^", + "@backstage/plugin-catalog-node": "workspace:^", + "express": "^4.17.1", + "express-promise-router": "^4.1.0", + "node-fetch": "^2.6.7", + "zod": "^3.22.4" + }, + "devDependencies": { + "@backstage/backend-test-utils": "workspace:^", + "@backstage/cli": "workspace:^", + "@backstage/plugin-auth-backend": "workspace:^", + "@backstage/plugin-auth-backend-module-guest-provider": "workspace:^", + "@types/express": "*", + "@types/supertest": "^2.0.8", + "msw": "^2.0.8", + "supertest": "^6.2.4" + } +} diff --git a/plugins/modern-backend/src/index.ts b/plugins/modern-backend/src/index.ts new file mode 100644 index 0000000000..33e742ca76 --- /dev/null +++ b/plugins/modern-backend/src/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2024 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { modernPlugin as default } from './plugin'; diff --git a/plugins/modern-backend/src/plugin.test.ts b/plugins/modern-backend/src/plugin.test.ts new file mode 100644 index 0000000000..975fb1ae70 --- /dev/null +++ b/plugins/modern-backend/src/plugin.test.ts @@ -0,0 +1,101 @@ +/* + * Copyright 2024 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + mockCredentials, + startTestBackend, +} from '@backstage/backend-test-utils'; +import { modernPlugin } from './plugin'; +import request from 'supertest'; +import { catalogServiceMock } from '@backstage/plugin-catalog-node/testUtils'; + +// TEMPLATE NOTE: +// Plugin tests are integration tests for your plugin, ensuring that all pieces +// work together end-to-end. You can still mock injected backend services +// however, just like anyway that installs your plugin might replace the +// services with their own implementations. +describe('plugin', () => { + it('should create and read TODO items', async () => { + const { server } = await startTestBackend({ + features: [modernPlugin], + }); + + await request(server).get('/api/modern/todos').expect(200, { + items: [], + }); + + const createRes = await request(server) + .post('/api/modern/todos') + .send({ title: 'My Todo' }); + + expect(createRes.status).toBe(201); + expect(createRes.body).toEqual({ + id: expect.any(String), + title: 'My Todo', + createdBy: mockCredentials.user().principal.userEntityRef, + createdAt: expect.any(String), + }); + + const createdTodoItem = createRes.body; + + await request(server) + .get('/api/modern/todos') + .expect(200, { + items: [createdTodoItem], + }); + + await request(server) + .get(`/api/modern/todos/${createdTodoItem.id}`) + .expect(200, createdTodoItem); + }); + + it('should create TODO item with catalog information', async () => { + const { server } = await startTestBackend({ + features: [ + modernPlugin, + catalogServiceMock.factory({ + entities: [ + { + apiVersion: 'backstage.io/v1alpha1', + kind: 'Component', + metadata: { + name: 'my-component', + namespace: 'default', + title: 'My Component', + }, + spec: { + type: 'service', + owner: 'me', + }, + }, + ], + }), + ], + }); + + const createRes = await request(server) + .post('/api/modern/todos') + .send({ title: 'My Todo', entityRef: 'component:default/my-component' }); + + expect(createRes.status).toBe(201); + expect(createRes.body).toEqual({ + id: expect.any(String), + title: '[My Component] My Todo', + createdBy: mockCredentials.user().principal.userEntityRef, + createdAt: expect.any(String), + }); + }); +}); diff --git a/plugins/modern-backend/src/plugin.ts b/plugins/modern-backend/src/plugin.ts new file mode 100644 index 0000000000..6db9427f2d --- /dev/null +++ b/plugins/modern-backend/src/plugin.ts @@ -0,0 +1,57 @@ +/* + * Copyright 2024 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + coreServices, + createBackendPlugin, +} from '@backstage/backend-plugin-api'; +import { createRouter } from './router'; +import { catalogServiceRef } from '@backstage/plugin-catalog-node/alpha'; +import { createTodoListService } from './services/TodoListService'; + +/** + * modernPlugin backend plugin + * + * @public + */ +export const modernPlugin = createBackendPlugin({ + pluginId: 'modern', + register(env) { + env.registerInit({ + deps: { + logger: coreServices.logger, + auth: coreServices.auth, + httpAuth: coreServices.httpAuth, + httpRouter: coreServices.httpRouter, + catalog: catalogServiceRef, + }, + async init({ logger, auth, httpAuth, httpRouter, catalog }) { + const todoListService = await createTodoListService({ + logger, + auth, + catalog, + }); + + httpRouter.use( + await createRouter({ + httpAuth, + todoListService, + }), + ); + }, + }); + }, +}); diff --git a/plugins/modern-backend/src/router.test.ts b/plugins/modern-backend/src/router.test.ts new file mode 100644 index 0000000000..70534703b4 --- /dev/null +++ b/plugins/modern-backend/src/router.test.ts @@ -0,0 +1,83 @@ +/* + * Copyright 2024 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + mockCredentials, + mockErrorHandler, + mockServices, +} from '@backstage/backend-test-utils'; +import express from 'express'; +import request from 'supertest'; + +import { createRouter } from './router'; +import { TodoListService } from './services/TodoListService/types'; + +const mockTodoItem = { + title: 'Do the thing', + id: '123', + createdBy: mockCredentials.user().principal.userEntityRef, + createdAt: new Date().toISOString(), +}; + +// TEMPLATE NOTE: +// Testing the router directly allows you to write a unit test that mocks the provided options. +describe('createRouter', () => { + let app: express.Express; + let todoListService: jest.Mocked; + + beforeEach(async () => { + todoListService = { + createTodo: jest.fn(), + listTodos: jest.fn(), + getTodo: jest.fn(), + }; + const router = await createRouter({ + httpAuth: mockServices.httpAuth(), + todoListService, + }); + app = express(); + app.use(router); + app.use(mockErrorHandler()); + }); + + it('should create a TODO', async () => { + todoListService.createTodo.mockResolvedValue(mockTodoItem); + + const response = await request(app).post('/todos').send({ + title: 'Do the thing', + }); + + expect(response.status).toBe(200); + expect(response.body).toEqual(mockTodoItem); + }); + + it('should not allow unauthenticated requests to create a TODO', async () => { + todoListService.createTodo.mockResolvedValue(mockTodoItem); + + // TEMPLATE NOTE: + // The HttpAuth mock service considers all requests to be authenticated as a + // mock user by default. In order to test other cases we need to explicitly + // pass an authorization header with mock credentials. + const response = await request(app) + .post('/todos') + .set('Authorization', mockCredentials.none.header()) + .send({ + title: 'Do the thing', + }); + + expect(response.status).toBe(401); + }); +}); diff --git a/plugins/modern-backend/src/router.ts b/plugins/modern-backend/src/router.ts new file mode 100644 index 0000000000..f4abbe7383 --- /dev/null +++ b/plugins/modern-backend/src/router.ts @@ -0,0 +1,67 @@ +/* + * Copyright 2024 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { HttpAuthService } from '@backstage/backend-plugin-api'; +import { InputError } from '@backstage/errors'; +import { z } from 'zod'; +import express from 'express'; +import Router from 'express-promise-router'; +import { TodoListService } from './services/TodoListService/types'; + +export async function createRouter({ + httpAuth, + todoListService, +}: { + httpAuth: HttpAuthService; + todoListService: TodoListService; +}): Promise { + const router = Router(); + router.use(express.json()); + + // TEMPLATE NOTE: + // Zod is a powerful library for data validation and recommended in particular + // for user-defined schemas. In this case we use it for input validation too. + // + // If you want to define a schema for your API we recommend using Backstage's + // OpenAPI tooling: https://backstage.io/docs/next/openapi/01-getting-started + const todoSchema = z.object({ + title: z.string(), + entityRef: z.string().optional(), + }); + + router.post('/todos', async (req, res) => { + const parsed = todoSchema.safeParse(req.body); + if (!parsed.success) { + throw new InputError(parsed.error.toString()); + } + + const result = await todoListService.createTodo(parsed.data, { + credentials: await httpAuth.credentials(req, { allow: ['user'] }), + }); + + res.status(201).json(result); + }); + + router.get('/todos', async (_req, res) => { + res.json(await todoListService.listTodos()); + }); + + router.get('/todos/:id', async (req, res) => { + res.json(await todoListService.getTodo({ id: req.params.id })); + }); + + return router; +} diff --git a/plugins/modern-backend/src/services/TodoListService/createTodoListService.ts b/plugins/modern-backend/src/services/TodoListService/createTodoListService.ts new file mode 100644 index 0000000000..a1b25b027f --- /dev/null +++ b/plugins/modern-backend/src/services/TodoListService/createTodoListService.ts @@ -0,0 +1,114 @@ +/* + * Copyright 2024 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AuthService, LoggerService } from '@backstage/backend-plugin-api'; +import { NotFoundError } from '@backstage/errors'; +import { catalogServiceRef } from '@backstage/plugin-catalog-node/alpha'; +import crypto from 'node:crypto'; +import { TodoItem, TodoListService } from './types'; + +// TEMPLATE NOTE: +// This is a simple in-memory todo list store. It is recommended to use a +// database to store data in a real application. See the database service +// documentation for more information on how to do this: +// https://backstage.io/docs/backend-system/core-services/database +export async function createTodoListService({ + auth, + logger, + catalog, +}: { + auth: AuthService; + logger: LoggerService; + catalog: typeof catalogServiceRef.T; +}): Promise { + logger.info('Initializing TodoListService'); + + const storedTodos = new Array(); + + return { + async createTodo(input, options) { + let title = input.title; + + // TEMPLATE NOTE: + // A common pattern for Backstage plugins is to pass an entity reference + // from the frontend to then fetch the entire entity from the catalog in the + // backend plugin. + if (input.entityRef) { + // TEMPLATE NOTE: + // Cross-plugin communication uses service-to-service authentication. The + // `AuthService` lets you generate a token that is valid for communication + // with the target plugin only. You must also provide credentials for the + // identity that you are making the request on behalf of. + // + // If you want to make a request using the plugin backend's own identity, + // you can access it via the `auth.getOwnServiceCredentials()` method. + // Beware that this bypasses any user permission checks. + const { token } = await auth.getPluginRequestToken({ + onBehalfOf: options.credentials, + targetPluginId: 'catalog', + }); + const entity = await catalog.getEntityByRef(input.entityRef, { + token, + }); + if (!entity) { + throw new NotFoundError( + `No entity found for ref '${input.entityRef}'`, + ); + } + + // TEMPLATE NOTE: + // Here you could read any form of data from the entity. A common use case + // is to read the value of a custom annotation for your plugin. You can + // read more about how to add custom annotations here: + // https://backstage.io/docs/features/software-catalog/extending-the-model#adding-a-new-annotation + // + // In this example we just use the entity title to decorate the todo item. + + const entityDisplay = entity.metadata.title ?? input.entityRef; + title = `[${entityDisplay}] ${input.title}`; + } + + const id = crypto.randomUUID(); + const createdBy = options.credentials.principal.userEntityRef; + const newTodo = { + title, + id, + createdBy, + createdAt: new Date().toISOString(), + }; + + storedTodos.push(newTodo); + + // TEMPLATE NOTE: + // The second argument of the logger methods can be used to pass structured metadata + logger.info('Created new todo item', { id, title, createdBy }); + + return newTodo; + }, + + async listTodos() { + return { items: Array.from(storedTodos) }; + }, + + async getTodo(request: { id: string }) { + const todo = storedTodos.find(item => item.id === request.id); + if (!todo) { + throw new NotFoundError(`No todo found with id '${request.id}'`); + } + return todo; + }, + }; +} diff --git a/plugins/modern-backend/src/services/TodoListService/index.ts b/plugins/modern-backend/src/services/TodoListService/index.ts new file mode 100644 index 0000000000..8f2547209b --- /dev/null +++ b/plugins/modern-backend/src/services/TodoListService/index.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2024 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export { createTodoListService } from './createTodoListService'; diff --git a/plugins/modern-backend/src/services/TodoListService/types.ts b/plugins/modern-backend/src/services/TodoListService/types.ts new file mode 100644 index 0000000000..07ff7cdc48 --- /dev/null +++ b/plugins/modern-backend/src/services/TodoListService/types.ts @@ -0,0 +1,43 @@ +/* + * Copyright 2024 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + BackstageCredentials, + BackstageUserPrincipal, +} from '@backstage/backend-plugin-api'; + +export interface TodoItem { + title: string; + id: string; + createdBy: string; + createdAt: string; +} + +export interface TodoListService { + createTodo( + input: { + title: string; + entityRef?: string; + }, + options: { + credentials: BackstageCredentials; + }, + ): Promise; + + listTodos(): Promise<{ items: TodoItem[] }>; + + getTodo(request: { id: string }): Promise; +} diff --git a/plugins/modern-backend/src/setupTests.ts b/plugins/modern-backend/src/setupTests.ts new file mode 100644 index 0000000000..b0f602d2d8 --- /dev/null +++ b/plugins/modern-backend/src/setupTests.ts @@ -0,0 +1,17 @@ +/* + * Copyright 2024 The Backstage Authors + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export {}; From 95999c5e2c09f7a045f938116b8ac8b241b372ea Mon Sep 17 00:00:00 2001 From: Patrik Oldsberg Date: Sat, 12 Oct 2024 11:36:53 +0200 Subject: [PATCH 2/7] cli: update backend plugin template Signed-off-by: Patrik Oldsberg --- .changeset/mighty-terms-peel.md | 5 + .../default-backend-plugin/dev/index.ts | 9 -- .../default-backend-plugin/dev/index.ts.hbs | 60 ++++++++++++ .../default-backend-plugin/package.json.hbs | 10 +- .../default-backend-plugin/src/index.ts.hbs | 1 - .../src/plugin.test.ts.hbs | 85 ++++++++++++++++ .../default-backend-plugin/src/plugin.ts.hbs | 30 +++--- .../default-backend-plugin/src/router.test.ts | 67 +++++++++++++ .../default-backend-plugin/src/router.ts | 51 ++++++++++ .../src/service/router.test.ts | 30 ------ .../src/service/router.ts | 28 ------ .../TodoListService/createTodoListService.ts | 98 +++++++++++++++++++ .../src/services/TodoListService/index.ts | 1 + .../src/services/TodoListService/types.ts | 27 +++++ 14 files changed, 415 insertions(+), 87 deletions(-) create mode 100644 .changeset/mighty-terms-peel.md delete mode 100644 packages/cli/templates/default-backend-plugin/dev/index.ts create mode 100644 packages/cli/templates/default-backend-plugin/dev/index.ts.hbs create mode 100644 packages/cli/templates/default-backend-plugin/src/plugin.test.ts.hbs create mode 100644 packages/cli/templates/default-backend-plugin/src/router.test.ts create mode 100644 packages/cli/templates/default-backend-plugin/src/router.ts delete mode 100644 packages/cli/templates/default-backend-plugin/src/service/router.test.ts delete mode 100644 packages/cli/templates/default-backend-plugin/src/service/router.ts create mode 100644 packages/cli/templates/default-backend-plugin/src/services/TodoListService/createTodoListService.ts create mode 100644 packages/cli/templates/default-backend-plugin/src/services/TodoListService/index.ts create mode 100644 packages/cli/templates/default-backend-plugin/src/services/TodoListService/types.ts diff --git a/.changeset/mighty-terms-peel.md b/.changeset/mighty-terms-peel.md new file mode 100644 index 0000000000..8804ee4556 --- /dev/null +++ b/.changeset/mighty-terms-peel.md @@ -0,0 +1,5 @@ +--- +'@backstage/cli': patch +--- + +The backend plugin template for the `new` command has been updated to provide more guidance and use a more modern structure. diff --git a/packages/cli/templates/default-backend-plugin/dev/index.ts b/packages/cli/templates/default-backend-plugin/dev/index.ts deleted file mode 100644 index 9d74c82508..0000000000 --- a/packages/cli/templates/default-backend-plugin/dev/index.ts +++ /dev/null @@ -1,9 +0,0 @@ -import { createBackend } from '@backstage/backend-defaults'; - -const backend = createBackend(); - -backend.add(import('@backstage/plugin-auth-backend')); -backend.add(import('@backstage/plugin-auth-backend-module-guest-provider')); -backend.add(import('../src')); - -backend.start(); diff --git a/packages/cli/templates/default-backend-plugin/dev/index.ts.hbs b/packages/cli/templates/default-backend-plugin/dev/index.ts.hbs new file mode 100644 index 0000000000..07dc091083 --- /dev/null +++ b/packages/cli/templates/default-backend-plugin/dev/index.ts.hbs @@ -0,0 +1,60 @@ +import { createBackend } from '@backstage/backend-defaults'; +import { mockServices } from '@backstage/backend-test-utils'; +import { catalogServiceMock } from '@backstage/plugin-catalog-node/testUtils'; + +// TEMPLATE NOTE: +// This is the development setup for your plugin that wires up a +// minimal backend that can use both real and mocked plugins and services. +// +// Start up the backend by running `yarn start` in the package directory. +// It's it's up and running, try out the following requests: +// +// Create a new todo item, standalone or for the sample component: +// +// curl http://localhost:7007/api/{{id}}/todos -H 'Content-Type: application/json' -d '{"title": "My Todo"}' +// curl http://localhost:7007/api/{{id}}/todos -H 'Content-Type: application/json' -d '{"title": "My Todo", "entityRef": "component:default/sample"}' +// +// List TODOs: +// +// curl http://localhost:7007/api/{{id}}/todos +// +// Explicitly make an unauthenticated request, or with service auth: +// +// curl http://localhost:7007/api/{{id}}/todos -H 'Authorization: Bearer mock-none-token' +// curl http://localhost:7007/api/{{id}}/todos -H 'Authorization: Bearer mock-service-token' + +const backend = createBackend(); + +// TEMPLATE NOTE: +// Mocking the auth and httpAuth service allows you to call your plugin API without +// having to authenticate. +// +// If you want to use real auth, you can install the following instead: +// backend.add(import('@backstage/plugin-auth-backend')); +// backend.add(import('@backstage/plugin-auth-backend-module-guest-provider')); +backend.add(mockServices.auth.factory()); +backend.add(mockServices.httpAuth.factory()); + +// TEMPLATE NOTE: +// Rather than using a real catalog you can use a mock with a fixed set of entities. +backend.add( + catalogServiceMock.factory({ + entities: [ + { + apiVersion: 'backstage.io/v1alpha1', + kind: 'Component', + metadata: { + name: 'sample', + title: 'Sample Component', + }, + spec: { + type: 'service', + }, + }, + ], + }), +); + +backend.add(import('../src')); + +backend.start(); diff --git a/packages/cli/templates/default-backend-plugin/package.json.hbs b/packages/cli/templates/default-backend-plugin/package.json.hbs index 6c25562c21..2f7c0931d8 100644 --- a/packages/cli/templates/default-backend-plugin/package.json.hbs +++ b/packages/cli/templates/default-backend-plugin/package.json.hbs @@ -30,19 +30,19 @@ "dependencies": { "@backstage/backend-defaults": "{{versionQuery '@backstage/backend-defaults'}}", "@backstage/backend-plugin-api": "{{versionQuery '@backstage/backend-plugin-api'}}", + "@backstage/catalog-client": "{{versionQuery '@backstage/catalog-client'}}", + "@backstage/errors": "{{versionQuery '@backstage/errors'}}", + "@backstage/plugin-catalog-node": "{{versionQuery '@backstage/plugin-catalog-node'}}", "express": "{{versionQuery 'express' '4.17.1'}}", "express-promise-router": "{{versionQuery 'express-promise-router' '4.1.0'}}", - "node-fetch": "{{versionQuery 'node-fetch' '2.6.7'}}" + "zod": "{{versionQuery 'zod' '3.22.4'}}" }, "devDependencies": { "@backstage/backend-test-utils": "{{versionQuery '@backstage/backend-test-utils'}}", "@backstage/cli": "{{versionQuery '@backstage/cli'}}", - "@backstage/plugin-auth-backend": "{{versionQuery '@backstage/plugin-auth-backend'}}", - "@backstage/plugin-auth-backend-module-guest-provider": "{{versionQuery '@backstage/plugin-auth-backend-module-guest-provider'}}", "@types/express": "{{versionQuery '@types/express' '4.17.6'}}", "@types/supertest": "{{versionQuery '@types/supertest' '2.0.12'}}", - "supertest": "{{versionQuery 'supertest' '6.2.4'}}", - "msw": "{{versionQuery 'msw' '2.3.1'}}" + "supertest": "{{versionQuery 'supertest' '6.2.4'}}" }, "files": [ "dist" diff --git a/packages/cli/templates/default-backend-plugin/src/index.ts.hbs b/packages/cli/templates/default-backend-plugin/src/index.ts.hbs index c04b266c28..be7f39c997 100644 --- a/packages/cli/templates/default-backend-plugin/src/index.ts.hbs +++ b/packages/cli/templates/default-backend-plugin/src/index.ts.hbs @@ -1,2 +1 @@ -export * from './service/router'; export { {{pluginVar}} as default } from './plugin'; diff --git a/packages/cli/templates/default-backend-plugin/src/plugin.test.ts.hbs b/packages/cli/templates/default-backend-plugin/src/plugin.test.ts.hbs new file mode 100644 index 0000000000..cd4b9fc438 --- /dev/null +++ b/packages/cli/templates/default-backend-plugin/src/plugin.test.ts.hbs @@ -0,0 +1,85 @@ +import { + mockCredentials, + startTestBackend, +} from '@backstage/backend-test-utils'; +import { {{pluginVar}} } from './plugin'; +import request from 'supertest'; +import { catalogServiceMock } from '@backstage/plugin-catalog-node/testUtils'; + +// TEMPLATE NOTE: +// Plugin tests are integration tests for your plugin, ensuring that all pieces +// work together end-to-end. You can still mock injected backend services +// however, just like anyway that installs your plugin might replace the +// services with their own implementations. +describe('plugin', () => { + it('should create and read TODO items', async () => { + const { server } = await startTestBackend({ + features: [{{pluginVar}}], + }); + + await request(server).get('/api/{{id}}/todos').expect(200, { + items: [], + }); + + const createRes = await request(server) + .post('/api/{{id}}/todos') + .send({ title: 'My Todo' }); + + expect(createRes.status).toBe(201); + expect(createRes.body).toEqual({ + id: expect.any(String), + title: 'My Todo', + createdBy: mockCredentials.user().principal.userEntityRef, + createdAt: expect.any(String), + }); + + const createdTodoItem = createRes.body; + + await request(server) + .get('/api/{{id}}/todos') + .expect(200, { + items: [createdTodoItem], + }); + + await request(server) + .get(`/api/{{id}}/todos/${createdTodoItem.id}`) + .expect(200, createdTodoItem); + }); + + it('should create TODO item with catalog information', async () => { + const { server } = await startTestBackend({ + features: [ + {{pluginVar}}, + catalogServiceMock.factory({ + entities: [ + { + apiVersion: 'backstage.io/v1alpha1', + kind: 'Component', + metadata: { + name: 'my-component', + namespace: 'default', + title: 'My Component', + }, + spec: { + type: 'service', + owner: 'me', + }, + }, + ], + }), + ], + }); + + const createRes = await request(server) + .post('/api/{{id}}/todos') + .send({ title: 'My Todo', entityRef: 'component:default/my-component' }); + + expect(createRes.status).toBe(201); + expect(createRes.body).toEqual({ + id: expect.any(String), + title: '[My Component] My Todo', + createdBy: mockCredentials.user().principal.userEntityRef, + createdAt: expect.any(String), + }); + }); +}); diff --git a/packages/cli/templates/default-backend-plugin/src/plugin.ts.hbs b/packages/cli/templates/default-backend-plugin/src/plugin.ts.hbs index bf04b43afe..a9cccc2af2 100644 --- a/packages/cli/templates/default-backend-plugin/src/plugin.ts.hbs +++ b/packages/cli/templates/default-backend-plugin/src/plugin.ts.hbs @@ -2,7 +2,9 @@ import { coreServices, createBackendPlugin, } from '@backstage/backend-plugin-api'; -import { createRouter } from './service/router'; +import { createRouter } from './router'; +import { catalogServiceRef } from '@backstage/plugin-catalog-node/alpha'; +import { createTodoListService } from './services/TodoListService'; /** * {{pluginVar}} backend plugin @@ -14,25 +16,25 @@ export const {{pluginVar}} = createBackendPlugin({ register(env) { env.registerInit({ deps: { - httpRouter: coreServices.httpRouter, logger: coreServices.logger, - config: coreServices.rootConfig, + auth: coreServices.auth, + httpAuth: coreServices.httpAuth, + httpRouter: coreServices.httpRouter, + catalog: catalogServiceRef, }, - async init({ - httpRouter, - logger, - config, - }) { + async init({ logger, auth, httpAuth, httpRouter, catalog }) { + const todoListService = await createTodoListService({ + logger, + auth, + catalog, + }); + httpRouter.use( await createRouter({ - logger, - config, + httpAuth, + todoListService, }), ); - httpRouter.addAuthPolicy({ - path: '/health', - allow: 'unauthenticated', - }); }, }); }, diff --git a/packages/cli/templates/default-backend-plugin/src/router.test.ts b/packages/cli/templates/default-backend-plugin/src/router.test.ts new file mode 100644 index 0000000000..86c91aab8e --- /dev/null +++ b/packages/cli/templates/default-backend-plugin/src/router.test.ts @@ -0,0 +1,67 @@ +import { + mockCredentials, + mockErrorHandler, + mockServices, +} from '@backstage/backend-test-utils'; +import express from 'express'; +import request from 'supertest'; + +import { createRouter } from './router'; +import { TodoListService } from './services/TodoListService/types'; + +const mockTodoItem = { + title: 'Do the thing', + id: '123', + createdBy: mockCredentials.user().principal.userEntityRef, + createdAt: new Date().toISOString(), +}; + +// TEMPLATE NOTE: +// Testing the router directly allows you to write a unit test that mocks the provided options. +describe('createRouter', () => { + let app: express.Express; + let todoListService: jest.Mocked; + + beforeEach(async () => { + todoListService = { + createTodo: jest.fn(), + listTodos: jest.fn(), + getTodo: jest.fn(), + }; + const router = await createRouter({ + httpAuth: mockServices.httpAuth(), + todoListService, + }); + app = express(); + app.use(router); + app.use(mockErrorHandler()); + }); + + it('should create a TODO', async () => { + todoListService.createTodo.mockResolvedValue(mockTodoItem); + + const response = await request(app).post('/todos').send({ + title: 'Do the thing', + }); + + expect(response.status).toBe(201); + expect(response.body).toEqual(mockTodoItem); + }); + + it('should not allow unauthenticated requests to create a TODO', async () => { + todoListService.createTodo.mockResolvedValue(mockTodoItem); + + // TEMPLATE NOTE: + // The HttpAuth mock service considers all requests to be authenticated as a + // mock user by default. In order to test other cases we need to explicitly + // pass an authorization header with mock credentials. + const response = await request(app) + .post('/todos') + .set('Authorization', mockCredentials.none.header()) + .send({ + title: 'Do the thing', + }); + + expect(response.status).toBe(401); + }); +}); diff --git a/packages/cli/templates/default-backend-plugin/src/router.ts b/packages/cli/templates/default-backend-plugin/src/router.ts new file mode 100644 index 0000000000..4c2ca49b67 --- /dev/null +++ b/packages/cli/templates/default-backend-plugin/src/router.ts @@ -0,0 +1,51 @@ +import { HttpAuthService } from '@backstage/backend-plugin-api'; +import { InputError } from '@backstage/errors'; +import { z } from 'zod'; +import express from 'express'; +import Router from 'express-promise-router'; +import { TodoListService } from './services/TodoListService/types'; + +export async function createRouter({ + httpAuth, + todoListService, +}: { + httpAuth: HttpAuthService; + todoListService: TodoListService; +}): Promise { + const router = Router(); + router.use(express.json()); + + // TEMPLATE NOTE: + // Zod is a powerful library for data validation and recommended in particular + // for user-defined schemas. In this case we use it for input validation too. + // + // If you want to define a schema for your API we recommend using Backstage's + // OpenAPI tooling: https://backstage.io/docs/next/openapi/01-getting-started + const todoSchema = z.object({ + title: z.string(), + entityRef: z.string().optional(), + }); + + router.post('/todos', async (req, res) => { + const parsed = todoSchema.safeParse(req.body); + if (!parsed.success) { + throw new InputError(parsed.error.toString()); + } + + const result = await todoListService.createTodo(parsed.data, { + credentials: await httpAuth.credentials(req, { allow: ['user'] }), + }); + + res.status(201).json(result); + }); + + router.get('/todos', async (_req, res) => { + res.json(await todoListService.listTodos()); + }); + + router.get('/todos/:id', async (req, res) => { + res.json(await todoListService.getTodo({ id: req.params.id })); + }); + + return router; +} diff --git a/packages/cli/templates/default-backend-plugin/src/service/router.test.ts b/packages/cli/templates/default-backend-plugin/src/service/router.test.ts deleted file mode 100644 index ed19d50d2b..0000000000 --- a/packages/cli/templates/default-backend-plugin/src/service/router.test.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { mockServices } from '@backstage/backend-test-utils'; -import express from 'express'; -import request from 'supertest'; - -import { createRouter } from './router'; - -describe('createRouter', () => { - let app: express.Express; - - beforeAll(async () => { - const router = await createRouter({ - logger: mockServices.logger.mock(), - config: mockServices.rootConfig(), - }); - app = express().use(router); - }); - - beforeEach(() => { - jest.resetAllMocks(); - }); - - describe('GET /health', () => { - it('returns ok', async () => { - const response = await request(app).get('/health'); - - expect(response.status).toEqual(200); - expect(response.body).toEqual({ status: 'ok' }); - }); - }); -}); diff --git a/packages/cli/templates/default-backend-plugin/src/service/router.ts b/packages/cli/templates/default-backend-plugin/src/service/router.ts deleted file mode 100644 index ced654aa82..0000000000 --- a/packages/cli/templates/default-backend-plugin/src/service/router.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { MiddlewareFactory } from '@backstage/backend-defaults/rootHttpRouter'; -import { LoggerService, RootConfigService } from '@backstage/backend-plugin-api'; -import express from 'express'; -import Router from 'express-promise-router'; - -export interface RouterOptions { - logger: LoggerService; - config: RootConfigService; -} - -export async function createRouter( - options: RouterOptions, -): Promise { - const { logger, config } = options; - - const router = Router(); - router.use(express.json()); - - router.get('/health', (_, response) => { - logger.info('PONG!'); - response.json({ status: 'ok' }); - }); - - const middleware = MiddlewareFactory.create({ logger, config }); - - router.use(middleware.error()); - return router; -} diff --git a/packages/cli/templates/default-backend-plugin/src/services/TodoListService/createTodoListService.ts b/packages/cli/templates/default-backend-plugin/src/services/TodoListService/createTodoListService.ts new file mode 100644 index 0000000000..90f6ad8d9e --- /dev/null +++ b/packages/cli/templates/default-backend-plugin/src/services/TodoListService/createTodoListService.ts @@ -0,0 +1,98 @@ +import { AuthService, LoggerService } from '@backstage/backend-plugin-api'; +import { NotFoundError } from '@backstage/errors'; +import { catalogServiceRef } from '@backstage/plugin-catalog-node/alpha'; +import crypto from 'node:crypto'; +import { TodoItem, TodoListService } from './types'; + +// TEMPLATE NOTE: +// This is a simple in-memory todo list store. It is recommended to use a +// database to store data in a real application. See the database service +// documentation for more information on how to do this: +// https://backstage.io/docs/backend-system/core-services/database +export async function createTodoListService({ + auth, + logger, + catalog, +}: { + auth: AuthService; + logger: LoggerService; + catalog: typeof catalogServiceRef.T; +}): Promise { + logger.info('Initializing TodoListService'); + + const storedTodos = new Array(); + + return { + async createTodo(input, options) { + let title = input.title; + + // TEMPLATE NOTE: + // A common pattern for Backstage plugins is to pass an entity reference + // from the frontend to then fetch the entire entity from the catalog in the + // backend plugin. + if (input.entityRef) { + // TEMPLATE NOTE: + // Cross-plugin communication uses service-to-service authentication. The + // `AuthService` lets you generate a token that is valid for communication + // with the target plugin only. You must also provide credentials for the + // identity that you are making the request on behalf of. + // + // If you want to make a request using the plugin backend's own identity, + // you can access it via the `auth.getOwnServiceCredentials()` method. + // Beware that this bypasses any user permission checks. + const { token } = await auth.getPluginRequestToken({ + onBehalfOf: options.credentials, + targetPluginId: 'catalog', + }); + const entity = await catalog.getEntityByRef(input.entityRef, { + token, + }); + if (!entity) { + throw new NotFoundError( + `No entity found for ref '${input.entityRef}'`, + ); + } + + // TEMPLATE NOTE: + // Here you could read any form of data from the entity. A common use case + // is to read the value of a custom annotation for your plugin. You can + // read more about how to add custom annotations here: + // https://backstage.io/docs/features/software-catalog/extending-the-model#adding-a-new-annotation + // + // In this example we just use the entity title to decorate the todo item. + + const entityDisplay = entity.metadata.title ?? input.entityRef; + title = `[${entityDisplay}] ${input.title}`; + } + + const id = crypto.randomUUID(); + const createdBy = options.credentials.principal.userEntityRef; + const newTodo = { + title, + id, + createdBy, + createdAt: new Date().toISOString(), + }; + + storedTodos.push(newTodo); + + // TEMPLATE NOTE: + // The second argument of the logger methods can be used to pass structured metadata + logger.info('Created new todo item', { id, title, createdBy }); + + return newTodo; + }, + + async listTodos() { + return { items: Array.from(storedTodos) }; + }, + + async getTodo(request: { id: string }) { + const todo = storedTodos.find(item => item.id === request.id); + if (!todo) { + throw new NotFoundError(`No todo found with id '${request.id}'`); + } + return todo; + }, + }; +} diff --git a/packages/cli/templates/default-backend-plugin/src/services/TodoListService/index.ts b/packages/cli/templates/default-backend-plugin/src/services/TodoListService/index.ts new file mode 100644 index 0000000000..1bc52001a8 --- /dev/null +++ b/packages/cli/templates/default-backend-plugin/src/services/TodoListService/index.ts @@ -0,0 +1 @@ +export { createTodoListService } from './createTodoListService'; diff --git a/packages/cli/templates/default-backend-plugin/src/services/TodoListService/types.ts b/packages/cli/templates/default-backend-plugin/src/services/TodoListService/types.ts new file mode 100644 index 0000000000..af895981a0 --- /dev/null +++ b/packages/cli/templates/default-backend-plugin/src/services/TodoListService/types.ts @@ -0,0 +1,27 @@ +import { + BackstageCredentials, + BackstageUserPrincipal, +} from '@backstage/backend-plugin-api'; + +export interface TodoItem { + title: string; + id: string; + createdBy: string; + createdAt: string; +} + +export interface TodoListService { + createTodo( + input: { + title: string; + entityRef?: string; + }, + options: { + credentials: BackstageCredentials; + }, + ): Promise; + + listTodos(): Promise<{ items: TodoItem[] }>; + + getTodo(request: { id: string }): Promise; +} From 26c719d4a37da1fa14011fb3171a419ff65edcf9 Mon Sep 17 00:00:00 2001 From: Patrik Oldsberg Date: Sat, 12 Oct 2024 11:44:39 +0200 Subject: [PATCH 3/7] cli: add missing templating package versions Signed-off-by: Patrik Oldsberg --- packages/cli/package.json | 6 +++ packages/cli/src/lib/version.ts | 6 +++ yarn.lock | 69 +++++++++++++++++++++++++++++++++ 3 files changed, 81 insertions(+) diff --git a/packages/cli/package.json b/packages/cli/package.json index 0ca580dd91..83d6623ed5 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -163,11 +163,17 @@ "@backstage/backend-common": "^0.25.0", "@backstage/backend-plugin-api": "workspace:^", "@backstage/backend-test-utils": "workspace:^", + "@backstage/catalog-client": "workspace:^", "@backstage/config": "workspace:^", "@backstage/core-app-api": "workspace:^", "@backstage/core-components": "workspace:^", "@backstage/core-plugin-api": "workspace:^", "@backstage/dev-utils": "workspace:^", + "@backstage/errors": "workspace:^", + "@backstage/plugin-auth-backend": "workspace:^", + "@backstage/plugin-auth-backend-module-guest-provider": "workspace:^", + "@backstage/plugin-catalog-node": "workspace:^", + "@backstage/plugin-scaffolder-node": "workspace:^", "@backstage/test-utils": "workspace:^", "@backstage/theme": "workspace:^", "@types/cross-spawn": "^6.0.2", diff --git a/packages/cli/src/lib/version.ts b/packages/cli/src/lib/version.ts index b2b3ae23cf..fb4a7105c3 100644 --- a/packages/cli/src/lib/version.ts +++ b/packages/cli/src/lib/version.ts @@ -34,16 +34,19 @@ leaving any imports in place. */ import { version as backendPluginApi } from '../../../../packages/backend-plugin-api/package.json'; import { version as backendTestUtils } from '../../../../packages/backend-test-utils/package.json'; +import { version as catalogClient } from '../../../../packages/catalog-client/package.json'; import { version as cli } from '../../../../packages/cli/package.json'; import { version as config } from '../../../../packages/config/package.json'; import { version as coreAppApi } from '../../../../packages/core-app-api/package.json'; import { version as coreComponents } from '../../../../packages/core-components/package.json'; import { version as corePluginApi } from '../../../../packages/core-plugin-api/package.json'; import { version as devUtils } from '../../../../packages/dev-utils/package.json'; +import { version as errors } from '../../../../packages/errors/package.json'; import { version as testUtils } from '../../../../packages/test-utils/package.json'; import { version as scaffolderNode } from '../../../../plugins/scaffolder-node/package.json'; import { version as authBackend } from '../../../../plugins/auth-backend/package.json'; import { version as authBackendModuleGuestProvider } from '../../../../plugins/auth-backend-module-guest-provider/package.json'; +import { version as catalogNode } from '../../../../plugins/catalog-node/package.json'; import { version as theme } from '../../../../packages/theme/package.json'; import { version as backendDefaults } from '../../../../packages/backend-defaults/package.json'; @@ -51,18 +54,21 @@ export const packageVersions: Record = { '@backstage/backend-defaults': backendDefaults, '@backstage/backend-plugin-api': backendPluginApi, '@backstage/backend-test-utils': backendTestUtils, + '@backstage/catalog-client': catalogClient, '@backstage/cli': cli, '@backstage/config': config, '@backstage/core-app-api': coreAppApi, '@backstage/core-components': coreComponents, '@backstage/core-plugin-api': corePluginApi, '@backstage/dev-utils': devUtils, + '@backstage/errors': errors, '@backstage/test-utils': testUtils, '@backstage/theme': theme, '@backstage/plugin-scaffolder-node': scaffolderNode, '@backstage/plugin-auth-backend': authBackend, '@backstage/plugin-auth-backend-module-guest-provider': authBackendModuleGuestProvider, + '@backstage/plugin-catalog-node': catalogNode, }; export function findVersion() { diff --git a/yarn.lock b/yarn.lock index 75503208bb..47b9244770 100644 --- a/yarn.lock +++ b/yarn.lock @@ -3913,6 +3913,7 @@ __metadata: "@backstage/backend-common": ^0.25.0 "@backstage/backend-plugin-api": "workspace:^" "@backstage/backend-test-utils": "workspace:^" + "@backstage/catalog-client": "workspace:^" "@backstage/catalog-model": "workspace:^" "@backstage/cli-common": "workspace:^" "@backstage/cli-node": "workspace:^" @@ -3925,6 +3926,10 @@ __metadata: "@backstage/errors": "workspace:^" "@backstage/eslint-plugin": "workspace:^" "@backstage/integration": "workspace:^" + "@backstage/plugin-auth-backend": "workspace:^" + "@backstage/plugin-auth-backend-module-guest-provider": "workspace:^" + "@backstage/plugin-catalog-node": "workspace:^" + "@backstage/plugin-scaffolder-node": "workspace:^" "@backstage/release-manifests": "workspace:^" "@backstage/test-utils": "workspace:^" "@backstage/theme": "workspace:^" @@ -6842,6 +6847,30 @@ __metadata: languageName: unknown linkType: soft +"@backstage/plugin-modern-backend@workspace:plugins/modern-backend": + version: 0.0.0-use.local + resolution: "@backstage/plugin-modern-backend@workspace:plugins/modern-backend" + dependencies: + "@backstage/backend-defaults": "workspace:^" + "@backstage/backend-plugin-api": "workspace:^" + "@backstage/backend-test-utils": "workspace:^" + "@backstage/catalog-client": "workspace:^" + "@backstage/cli": "workspace:^" + "@backstage/errors": "workspace:^" + "@backstage/plugin-auth-backend": "workspace:^" + "@backstage/plugin-auth-backend-module-guest-provider": "workspace:^" + "@backstage/plugin-catalog-node": "workspace:^" + "@types/express": "*" + "@types/supertest": ^2.0.8 + express: ^4.17.1 + express-promise-router: ^4.1.0 + msw: ^2.0.8 + node-fetch: ^2.6.7 + supertest: ^6.2.4 + zod: ^3.22.4 + languageName: unknown + linkType: soft + "@backstage/plugin-notifications-backend-module-email@workspace:plugins/notifications-backend-module-email": version: 0.0.0-use.local resolution: "@backstage/plugin-notifications-backend-module-email@workspace:plugins/notifications-backend-module-email" @@ -27934,6 +27963,18 @@ __metadata: languageName: node linkType: hard +"formidable@npm:^2.1.2": + version: 2.1.2 + resolution: "formidable@npm:2.1.2" + dependencies: + dezalgo: ^1.0.4 + hexoid: ^1.0.0 + once: ^1.4.0 + qs: ^6.11.0 + checksum: 81c8e5d89f5eb873e992893468f0de22c01678ca3d315db62be0560f9de1c77d4faefc9b1f4575098eb2263b3c81ba1024833a9fc3206297ddbac88a4f69b7a8 + languageName: node + linkType: hard + "formidable@npm:^3.5.1": version: 3.5.1 resolution: "formidable@npm:3.5.1" @@ -42036,6 +42077,24 @@ __metadata: languageName: node linkType: hard +"superagent@npm:^8.1.2": + version: 8.1.2 + resolution: "superagent@npm:8.1.2" + dependencies: + component-emitter: ^1.3.0 + cookiejar: ^2.1.4 + debug: ^4.3.4 + fast-safe-stringify: ^2.1.1 + form-data: ^4.0.0 + formidable: ^2.1.2 + methods: ^1.1.2 + mime: 2.6.0 + qs: ^6.11.0 + semver: ^7.3.8 + checksum: f3601c5ccae34d5ba684a03703394b5d25931f4ae2e1e31a1de809f88a9400e997ece037f9accf148a21c408f950dc829db1e4e23576a7f9fe0efa79fd5c9d2f + languageName: node + linkType: hard + "superagent@npm:^9.0.1": version: 9.0.2 resolution: "superagent@npm:9.0.2" @@ -42053,6 +42112,16 @@ __metadata: languageName: node linkType: hard +"supertest@npm:^6.2.4": + version: 6.3.4 + resolution: "supertest@npm:6.3.4" + dependencies: + methods: ^1.1.2 + superagent: ^8.1.2 + checksum: 875c6fa7940f21e5be9bb646579cdb030d4057bf2da643e125e1f0480add1200395d2b17e10b8e54e1009efc63e047422501e9eb30e12828668498c0910f295f + languageName: node + linkType: hard + "supertest@npm:^7.0.0": version: 7.0.0 resolution: "supertest@npm:7.0.0" From bb8bb7790e35adc3beaa8eede128a2f8e448c371 Mon Sep 17 00:00:00 2001 From: Patrik Oldsberg Date: Sat, 12 Oct 2024 11:55:55 +0200 Subject: [PATCH 4/7] plugins: remove temporary modern-backend plugin Signed-off-by: Patrik Oldsberg --- plugins/modern-backend/.eslintrc.js | 1 - plugins/modern-backend/README.md | 14 --- plugins/modern-backend/catalog-info.yaml | 9 -- plugins/modern-backend/dev/index.ts | 74 ------------ plugins/modern-backend/package.json | 48 -------- plugins/modern-backend/src/index.ts | 17 --- plugins/modern-backend/src/plugin.test.ts | 101 ---------------- plugins/modern-backend/src/plugin.ts | 57 --------- plugins/modern-backend/src/router.test.ts | 83 ------------- plugins/modern-backend/src/router.ts | 67 ---------- .../TodoListService/createTodoListService.ts | 114 ------------------ .../src/services/TodoListService/index.ts | 17 --- .../src/services/TodoListService/types.ts | 43 ------- plugins/modern-backend/src/setupTests.ts | 17 --- yarn.lock | 64 ---------- 15 files changed, 726 deletions(-) delete mode 100644 plugins/modern-backend/.eslintrc.js delete mode 100644 plugins/modern-backend/README.md delete mode 100644 plugins/modern-backend/catalog-info.yaml delete mode 100644 plugins/modern-backend/dev/index.ts delete mode 100644 plugins/modern-backend/package.json delete mode 100644 plugins/modern-backend/src/index.ts delete mode 100644 plugins/modern-backend/src/plugin.test.ts delete mode 100644 plugins/modern-backend/src/plugin.ts delete mode 100644 plugins/modern-backend/src/router.test.ts delete mode 100644 plugins/modern-backend/src/router.ts delete mode 100644 plugins/modern-backend/src/services/TodoListService/createTodoListService.ts delete mode 100644 plugins/modern-backend/src/services/TodoListService/index.ts delete mode 100644 plugins/modern-backend/src/services/TodoListService/types.ts delete mode 100644 plugins/modern-backend/src/setupTests.ts diff --git a/plugins/modern-backend/.eslintrc.js b/plugins/modern-backend/.eslintrc.js deleted file mode 100644 index e2a53a6ad2..0000000000 --- a/plugins/modern-backend/.eslintrc.js +++ /dev/null @@ -1 +0,0 @@ -module.exports = require('@backstage/cli/config/eslint-factory')(__dirname); diff --git a/plugins/modern-backend/README.md b/plugins/modern-backend/README.md deleted file mode 100644 index 929b0a189f..0000000000 --- a/plugins/modern-backend/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# modern - -Welcome to the modern backend plugin! - -_This plugin was created through the Backstage CLI_ - -## Getting started - -Your plugin has been added to the example app in this repository, meaning you'll be able to access it by running `yarn -start` in the root directory, and then navigating to [/modern/health](http://localhost:7007/api/modern/health). - -You can also serve the plugin in isolation by running `yarn start` in the plugin directory. -This method of serving the plugin provides quicker iteration speed and a faster startup and hot reloads. -It is only meant for local development, and the setup for it can be found inside the [/dev](./dev) directory. diff --git a/plugins/modern-backend/catalog-info.yaml b/plugins/modern-backend/catalog-info.yaml deleted file mode 100644 index fd4b9dc0ba..0000000000 --- a/plugins/modern-backend/catalog-info.yaml +++ /dev/null @@ -1,9 +0,0 @@ -apiVersion: backstage.io/v1alpha1 -kind: Component -metadata: - name: backstage-plugin-modern-backend - title: '@backstage/plugin-modern-backend' -spec: - lifecycle: experimental - type: backstage-backend-plugin - owner: maintainers diff --git a/plugins/modern-backend/dev/index.ts b/plugins/modern-backend/dev/index.ts deleted file mode 100644 index 393f979bed..0000000000 --- a/plugins/modern-backend/dev/index.ts +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2024 The Backstage Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -import { createBackend } from '@backstage/backend-defaults'; -import { mockServices } from '@backstage/backend-test-utils'; -import { catalogServiceMock } from '@backstage/plugin-catalog-node/testUtils'; - -// TEMPLATE NOTE: -// This is the development setup for your plugin that wires up a -// minimal backend that can use both real and mocked plugins and services. -// -// Start up the backend by running `yarn start` in the package directory. -// It's it's up and running, try out the following requests: -// -// Create a new todo item: -// -// curl http://localhost:7007/api/modern/todos -H 'Content-Type: application/json' -d '{"title": "My Todo"}' -// -// List TODOs: -// -// curl http://localhost:7007/api/modern/todos -// -// Explicitly make an unauthenticated request, or with service auth: -// -// curl http://localhost:7007/api/modern/todos -H 'Authorization: Bearer mock-none-token' -// curl http://localhost:7007/api/modern/todos -H 'Authorization: Bearer mock-service-token' - -const backend = createBackend(); - -// TEMPLATE NOTE: -// Mocking the auth and httpAuth service allows you to call your plugin API without -// having to authenticate. -// -// If you want to use real auth, you can install the following instead: -// backend.add(import('@backstage/plugin-auth-backend')); -// backend.add(import('@backstage/plugin-auth-backend-module-guest-provider')); -backend.add(mockServices.auth.factory()); -backend.add(mockServices.httpAuth.factory()); - -// TEMPLATE NOTE: -// Rather than using a real catalog you can use a mock with a fixed set of entities. -backend.add( - catalogServiceMock.factory({ - entities: [ - { - apiVersion: 'backstage.io/v1alpha1', - kind: 'Component', - metadata: { - name: 'sample', - title: 'Sample Component', - }, - spec: { - type: 'service', - }, - }, - ], - }), -); - -backend.add(import('../src')); - -backend.start(); diff --git a/plugins/modern-backend/package.json b/plugins/modern-backend/package.json deleted file mode 100644 index def56e6ce3..0000000000 --- a/plugins/modern-backend/package.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "name": "@backstage/plugin-modern-backend", - "version": "0.0.0", - "backstage": { - "role": "backend-plugin" - }, - "publishConfig": { - "access": "public", - "main": "dist/index.cjs.js", - "types": "dist/index.d.ts" - }, - "license": "Apache-2.0", - "main": "src/index.ts", - "types": "src/index.ts", - "files": [ - "dist" - ], - "scripts": { - "build": "backstage-cli package build", - "clean": "backstage-cli package clean", - "lint": "backstage-cli package lint", - "prepack": "backstage-cli package prepack", - "postpack": "backstage-cli package postpack", - "start": "backstage-cli package start", - "test": "backstage-cli package test" - }, - "dependencies": { - "@backstage/backend-defaults": "workspace:^", - "@backstage/backend-plugin-api": "workspace:^", - "@backstage/catalog-client": "workspace:^", - "@backstage/errors": "workspace:^", - "@backstage/plugin-catalog-node": "workspace:^", - "express": "^4.17.1", - "express-promise-router": "^4.1.0", - "node-fetch": "^2.6.7", - "zod": "^3.22.4" - }, - "devDependencies": { - "@backstage/backend-test-utils": "workspace:^", - "@backstage/cli": "workspace:^", - "@backstage/plugin-auth-backend": "workspace:^", - "@backstage/plugin-auth-backend-module-guest-provider": "workspace:^", - "@types/express": "*", - "@types/supertest": "^2.0.8", - "msw": "^2.0.8", - "supertest": "^6.2.4" - } -} diff --git a/plugins/modern-backend/src/index.ts b/plugins/modern-backend/src/index.ts deleted file mode 100644 index 33e742ca76..0000000000 --- a/plugins/modern-backend/src/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright 2024 The Backstage Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export { modernPlugin as default } from './plugin'; diff --git a/plugins/modern-backend/src/plugin.test.ts b/plugins/modern-backend/src/plugin.test.ts deleted file mode 100644 index 975fb1ae70..0000000000 --- a/plugins/modern-backend/src/plugin.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -/* - * Copyright 2024 The Backstage Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { - mockCredentials, - startTestBackend, -} from '@backstage/backend-test-utils'; -import { modernPlugin } from './plugin'; -import request from 'supertest'; -import { catalogServiceMock } from '@backstage/plugin-catalog-node/testUtils'; - -// TEMPLATE NOTE: -// Plugin tests are integration tests for your plugin, ensuring that all pieces -// work together end-to-end. You can still mock injected backend services -// however, just like anyway that installs your plugin might replace the -// services with their own implementations. -describe('plugin', () => { - it('should create and read TODO items', async () => { - const { server } = await startTestBackend({ - features: [modernPlugin], - }); - - await request(server).get('/api/modern/todos').expect(200, { - items: [], - }); - - const createRes = await request(server) - .post('/api/modern/todos') - .send({ title: 'My Todo' }); - - expect(createRes.status).toBe(201); - expect(createRes.body).toEqual({ - id: expect.any(String), - title: 'My Todo', - createdBy: mockCredentials.user().principal.userEntityRef, - createdAt: expect.any(String), - }); - - const createdTodoItem = createRes.body; - - await request(server) - .get('/api/modern/todos') - .expect(200, { - items: [createdTodoItem], - }); - - await request(server) - .get(`/api/modern/todos/${createdTodoItem.id}`) - .expect(200, createdTodoItem); - }); - - it('should create TODO item with catalog information', async () => { - const { server } = await startTestBackend({ - features: [ - modernPlugin, - catalogServiceMock.factory({ - entities: [ - { - apiVersion: 'backstage.io/v1alpha1', - kind: 'Component', - metadata: { - name: 'my-component', - namespace: 'default', - title: 'My Component', - }, - spec: { - type: 'service', - owner: 'me', - }, - }, - ], - }), - ], - }); - - const createRes = await request(server) - .post('/api/modern/todos') - .send({ title: 'My Todo', entityRef: 'component:default/my-component' }); - - expect(createRes.status).toBe(201); - expect(createRes.body).toEqual({ - id: expect.any(String), - title: '[My Component] My Todo', - createdBy: mockCredentials.user().principal.userEntityRef, - createdAt: expect.any(String), - }); - }); -}); diff --git a/plugins/modern-backend/src/plugin.ts b/plugins/modern-backend/src/plugin.ts deleted file mode 100644 index 6db9427f2d..0000000000 --- a/plugins/modern-backend/src/plugin.ts +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2024 The Backstage Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { - coreServices, - createBackendPlugin, -} from '@backstage/backend-plugin-api'; -import { createRouter } from './router'; -import { catalogServiceRef } from '@backstage/plugin-catalog-node/alpha'; -import { createTodoListService } from './services/TodoListService'; - -/** - * modernPlugin backend plugin - * - * @public - */ -export const modernPlugin = createBackendPlugin({ - pluginId: 'modern', - register(env) { - env.registerInit({ - deps: { - logger: coreServices.logger, - auth: coreServices.auth, - httpAuth: coreServices.httpAuth, - httpRouter: coreServices.httpRouter, - catalog: catalogServiceRef, - }, - async init({ logger, auth, httpAuth, httpRouter, catalog }) { - const todoListService = await createTodoListService({ - logger, - auth, - catalog, - }); - - httpRouter.use( - await createRouter({ - httpAuth, - todoListService, - }), - ); - }, - }); - }, -}); diff --git a/plugins/modern-backend/src/router.test.ts b/plugins/modern-backend/src/router.test.ts deleted file mode 100644 index 70534703b4..0000000000 --- a/plugins/modern-backend/src/router.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2024 The Backstage Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { - mockCredentials, - mockErrorHandler, - mockServices, -} from '@backstage/backend-test-utils'; -import express from 'express'; -import request from 'supertest'; - -import { createRouter } from './router'; -import { TodoListService } from './services/TodoListService/types'; - -const mockTodoItem = { - title: 'Do the thing', - id: '123', - createdBy: mockCredentials.user().principal.userEntityRef, - createdAt: new Date().toISOString(), -}; - -// TEMPLATE NOTE: -// Testing the router directly allows you to write a unit test that mocks the provided options. -describe('createRouter', () => { - let app: express.Express; - let todoListService: jest.Mocked; - - beforeEach(async () => { - todoListService = { - createTodo: jest.fn(), - listTodos: jest.fn(), - getTodo: jest.fn(), - }; - const router = await createRouter({ - httpAuth: mockServices.httpAuth(), - todoListService, - }); - app = express(); - app.use(router); - app.use(mockErrorHandler()); - }); - - it('should create a TODO', async () => { - todoListService.createTodo.mockResolvedValue(mockTodoItem); - - const response = await request(app).post('/todos').send({ - title: 'Do the thing', - }); - - expect(response.status).toBe(200); - expect(response.body).toEqual(mockTodoItem); - }); - - it('should not allow unauthenticated requests to create a TODO', async () => { - todoListService.createTodo.mockResolvedValue(mockTodoItem); - - // TEMPLATE NOTE: - // The HttpAuth mock service considers all requests to be authenticated as a - // mock user by default. In order to test other cases we need to explicitly - // pass an authorization header with mock credentials. - const response = await request(app) - .post('/todos') - .set('Authorization', mockCredentials.none.header()) - .send({ - title: 'Do the thing', - }); - - expect(response.status).toBe(401); - }); -}); diff --git a/plugins/modern-backend/src/router.ts b/plugins/modern-backend/src/router.ts deleted file mode 100644 index f4abbe7383..0000000000 --- a/plugins/modern-backend/src/router.ts +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2024 The Backstage Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { HttpAuthService } from '@backstage/backend-plugin-api'; -import { InputError } from '@backstage/errors'; -import { z } from 'zod'; -import express from 'express'; -import Router from 'express-promise-router'; -import { TodoListService } from './services/TodoListService/types'; - -export async function createRouter({ - httpAuth, - todoListService, -}: { - httpAuth: HttpAuthService; - todoListService: TodoListService; -}): Promise { - const router = Router(); - router.use(express.json()); - - // TEMPLATE NOTE: - // Zod is a powerful library for data validation and recommended in particular - // for user-defined schemas. In this case we use it for input validation too. - // - // If you want to define a schema for your API we recommend using Backstage's - // OpenAPI tooling: https://backstage.io/docs/next/openapi/01-getting-started - const todoSchema = z.object({ - title: z.string(), - entityRef: z.string().optional(), - }); - - router.post('/todos', async (req, res) => { - const parsed = todoSchema.safeParse(req.body); - if (!parsed.success) { - throw new InputError(parsed.error.toString()); - } - - const result = await todoListService.createTodo(parsed.data, { - credentials: await httpAuth.credentials(req, { allow: ['user'] }), - }); - - res.status(201).json(result); - }); - - router.get('/todos', async (_req, res) => { - res.json(await todoListService.listTodos()); - }); - - router.get('/todos/:id', async (req, res) => { - res.json(await todoListService.getTodo({ id: req.params.id })); - }); - - return router; -} diff --git a/plugins/modern-backend/src/services/TodoListService/createTodoListService.ts b/plugins/modern-backend/src/services/TodoListService/createTodoListService.ts deleted file mode 100644 index a1b25b027f..0000000000 --- a/plugins/modern-backend/src/services/TodoListService/createTodoListService.ts +++ /dev/null @@ -1,114 +0,0 @@ -/* - * Copyright 2024 The Backstage Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { AuthService, LoggerService } from '@backstage/backend-plugin-api'; -import { NotFoundError } from '@backstage/errors'; -import { catalogServiceRef } from '@backstage/plugin-catalog-node/alpha'; -import crypto from 'node:crypto'; -import { TodoItem, TodoListService } from './types'; - -// TEMPLATE NOTE: -// This is a simple in-memory todo list store. It is recommended to use a -// database to store data in a real application. See the database service -// documentation for more information on how to do this: -// https://backstage.io/docs/backend-system/core-services/database -export async function createTodoListService({ - auth, - logger, - catalog, -}: { - auth: AuthService; - logger: LoggerService; - catalog: typeof catalogServiceRef.T; -}): Promise { - logger.info('Initializing TodoListService'); - - const storedTodos = new Array(); - - return { - async createTodo(input, options) { - let title = input.title; - - // TEMPLATE NOTE: - // A common pattern for Backstage plugins is to pass an entity reference - // from the frontend to then fetch the entire entity from the catalog in the - // backend plugin. - if (input.entityRef) { - // TEMPLATE NOTE: - // Cross-plugin communication uses service-to-service authentication. The - // `AuthService` lets you generate a token that is valid for communication - // with the target plugin only. You must also provide credentials for the - // identity that you are making the request on behalf of. - // - // If you want to make a request using the plugin backend's own identity, - // you can access it via the `auth.getOwnServiceCredentials()` method. - // Beware that this bypasses any user permission checks. - const { token } = await auth.getPluginRequestToken({ - onBehalfOf: options.credentials, - targetPluginId: 'catalog', - }); - const entity = await catalog.getEntityByRef(input.entityRef, { - token, - }); - if (!entity) { - throw new NotFoundError( - `No entity found for ref '${input.entityRef}'`, - ); - } - - // TEMPLATE NOTE: - // Here you could read any form of data from the entity. A common use case - // is to read the value of a custom annotation for your plugin. You can - // read more about how to add custom annotations here: - // https://backstage.io/docs/features/software-catalog/extending-the-model#adding-a-new-annotation - // - // In this example we just use the entity title to decorate the todo item. - - const entityDisplay = entity.metadata.title ?? input.entityRef; - title = `[${entityDisplay}] ${input.title}`; - } - - const id = crypto.randomUUID(); - const createdBy = options.credentials.principal.userEntityRef; - const newTodo = { - title, - id, - createdBy, - createdAt: new Date().toISOString(), - }; - - storedTodos.push(newTodo); - - // TEMPLATE NOTE: - // The second argument of the logger methods can be used to pass structured metadata - logger.info('Created new todo item', { id, title, createdBy }); - - return newTodo; - }, - - async listTodos() { - return { items: Array.from(storedTodos) }; - }, - - async getTodo(request: { id: string }) { - const todo = storedTodos.find(item => item.id === request.id); - if (!todo) { - throw new NotFoundError(`No todo found with id '${request.id}'`); - } - return todo; - }, - }; -} diff --git a/plugins/modern-backend/src/services/TodoListService/index.ts b/plugins/modern-backend/src/services/TodoListService/index.ts deleted file mode 100644 index 8f2547209b..0000000000 --- a/plugins/modern-backend/src/services/TodoListService/index.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright 2024 The Backstage Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export { createTodoListService } from './createTodoListService'; diff --git a/plugins/modern-backend/src/services/TodoListService/types.ts b/plugins/modern-backend/src/services/TodoListService/types.ts deleted file mode 100644 index 07ff7cdc48..0000000000 --- a/plugins/modern-backend/src/services/TodoListService/types.ts +++ /dev/null @@ -1,43 +0,0 @@ -/* - * Copyright 2024 The Backstage Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -import { - BackstageCredentials, - BackstageUserPrincipal, -} from '@backstage/backend-plugin-api'; - -export interface TodoItem { - title: string; - id: string; - createdBy: string; - createdAt: string; -} - -export interface TodoListService { - createTodo( - input: { - title: string; - entityRef?: string; - }, - options: { - credentials: BackstageCredentials; - }, - ): Promise; - - listTodos(): Promise<{ items: TodoItem[] }>; - - getTodo(request: { id: string }): Promise; -} diff --git a/plugins/modern-backend/src/setupTests.ts b/plugins/modern-backend/src/setupTests.ts deleted file mode 100644 index b0f602d2d8..0000000000 --- a/plugins/modern-backend/src/setupTests.ts +++ /dev/null @@ -1,17 +0,0 @@ -/* - * Copyright 2024 The Backstage Authors - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -export {}; diff --git a/yarn.lock b/yarn.lock index 47b9244770..2d83745f3b 100644 --- a/yarn.lock +++ b/yarn.lock @@ -6847,30 +6847,6 @@ __metadata: languageName: unknown linkType: soft -"@backstage/plugin-modern-backend@workspace:plugins/modern-backend": - version: 0.0.0-use.local - resolution: "@backstage/plugin-modern-backend@workspace:plugins/modern-backend" - dependencies: - "@backstage/backend-defaults": "workspace:^" - "@backstage/backend-plugin-api": "workspace:^" - "@backstage/backend-test-utils": "workspace:^" - "@backstage/catalog-client": "workspace:^" - "@backstage/cli": "workspace:^" - "@backstage/errors": "workspace:^" - "@backstage/plugin-auth-backend": "workspace:^" - "@backstage/plugin-auth-backend-module-guest-provider": "workspace:^" - "@backstage/plugin-catalog-node": "workspace:^" - "@types/express": "*" - "@types/supertest": ^2.0.8 - express: ^4.17.1 - express-promise-router: ^4.1.0 - msw: ^2.0.8 - node-fetch: ^2.6.7 - supertest: ^6.2.4 - zod: ^3.22.4 - languageName: unknown - linkType: soft - "@backstage/plugin-notifications-backend-module-email@workspace:plugins/notifications-backend-module-email": version: 0.0.0-use.local resolution: "@backstage/plugin-notifications-backend-module-email@workspace:plugins/notifications-backend-module-email" @@ -27963,18 +27939,6 @@ __metadata: languageName: node linkType: hard -"formidable@npm:^2.1.2": - version: 2.1.2 - resolution: "formidable@npm:2.1.2" - dependencies: - dezalgo: ^1.0.4 - hexoid: ^1.0.0 - once: ^1.4.0 - qs: ^6.11.0 - checksum: 81c8e5d89f5eb873e992893468f0de22c01678ca3d315db62be0560f9de1c77d4faefc9b1f4575098eb2263b3c81ba1024833a9fc3206297ddbac88a4f69b7a8 - languageName: node - linkType: hard - "formidable@npm:^3.5.1": version: 3.5.1 resolution: "formidable@npm:3.5.1" @@ -42077,24 +42041,6 @@ __metadata: languageName: node linkType: hard -"superagent@npm:^8.1.2": - version: 8.1.2 - resolution: "superagent@npm:8.1.2" - dependencies: - component-emitter: ^1.3.0 - cookiejar: ^2.1.4 - debug: ^4.3.4 - fast-safe-stringify: ^2.1.1 - form-data: ^4.0.0 - formidable: ^2.1.2 - methods: ^1.1.2 - mime: 2.6.0 - qs: ^6.11.0 - semver: ^7.3.8 - checksum: f3601c5ccae34d5ba684a03703394b5d25931f4ae2e1e31a1de809f88a9400e997ece037f9accf148a21c408f950dc829db1e4e23576a7f9fe0efa79fd5c9d2f - languageName: node - linkType: hard - "superagent@npm:^9.0.1": version: 9.0.2 resolution: "superagent@npm:9.0.2" @@ -42112,16 +42058,6 @@ __metadata: languageName: node linkType: hard -"supertest@npm:^6.2.4": - version: 6.3.4 - resolution: "supertest@npm:6.3.4" - dependencies: - methods: ^1.1.2 - superagent: ^8.1.2 - checksum: 875c6fa7940f21e5be9bb646579cdb030d4057bf2da643e125e1f0480add1200395d2b17e10b8e54e1009efc63e047422501e9eb30e12828668498c0910f295f - languageName: node - linkType: hard - "supertest@npm:^7.0.0": version: 7.0.0 resolution: "supertest@npm:7.0.0" From a05fcbbe632b1db08a7ab91f805c2dd03316dc7b Mon Sep 17 00:00:00 2001 From: Patrik Oldsberg Date: Sat, 12 Oct 2024 12:09:28 +0200 Subject: [PATCH 5/7] cli: update backend plugin template README Signed-off-by: Patrik Oldsberg --- .../default-backend-plugin/README.md.hbs | 30 ++++++++++++++----- 1 file changed, 22 insertions(+), 8 deletions(-) diff --git a/packages/cli/templates/default-backend-plugin/README.md.hbs b/packages/cli/templates/default-backend-plugin/README.md.hbs index d519c3f459..00e83a33ec 100644 --- a/packages/cli/templates/default-backend-plugin/README.md.hbs +++ b/packages/cli/templates/default-backend-plugin/README.md.hbs @@ -1,14 +1,28 @@ # {{id}} -Welcome to the {{id}} backend plugin! +This plugin backend was templated using the Backstage CLI. You should replace this text with a description of your plugin backend. -_This plugin was created through the Backstage CLI_ +## Installation -## Getting started +This plugin is installed via the `{{name}}` package. To install it to your backend package, run the following command: -Your plugin has been added to the example app in this repository, meaning you'll be able to access it by running `yarn -start` in the root directory, and then navigating to [/{{id}}/health](http://localhost:7007/api/{{id}}/health). +```bash +# From your root directory +yarn --cwd packages/backend add {{name}} +``` -You can also serve the plugin in isolation by running `yarn start` in the plugin directory. -This method of serving the plugin provides quicker iteration speed and a faster startup and hot reloads. -It is only meant for local development, and the setup for it can be found inside the [/dev](./dev) directory. +Then add the plugin to your backend in `packages/backend/src/index.ts`: + +```ts +const backend = createBackend(); +// ... +backend.add(import('{{name}}')); +``` + +## Development + +This plugin backend can be started in a standalone mode from directly in this +package with `yarn start`. It is a limited setup that is most convenient when +developing the plugin backend itself. + +If you want to run the entire project, including the frontend, run `yarn dev` from the root directory. From 11a489f2fafa49a725480c8e4e0ef5c47db30e37 Mon Sep 17 00:00:00 2001 From: Patrik Oldsberg Date: Sat, 12 Oct 2024 18:06:35 +0200 Subject: [PATCH 6/7] Apply suggestions from code review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-authored-by: Fredrik Adelöw Signed-off-by: Patrik Oldsberg --- packages/cli/templates/default-backend-plugin/dev/index.ts.hbs | 2 +- .../cli/templates/default-backend-plugin/src/plugin.test.ts.hbs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/cli/templates/default-backend-plugin/dev/index.ts.hbs b/packages/cli/templates/default-backend-plugin/dev/index.ts.hbs index 07dc091083..ce1d2919c9 100644 --- a/packages/cli/templates/default-backend-plugin/dev/index.ts.hbs +++ b/packages/cli/templates/default-backend-plugin/dev/index.ts.hbs @@ -7,7 +7,7 @@ import { catalogServiceMock } from '@backstage/plugin-catalog-node/testUtils'; // minimal backend that can use both real and mocked plugins and services. // // Start up the backend by running `yarn start` in the package directory. -// It's it's up and running, try out the following requests: +// Once it's up and running, try out the following requests: // // Create a new todo item, standalone or for the sample component: // diff --git a/packages/cli/templates/default-backend-plugin/src/plugin.test.ts.hbs b/packages/cli/templates/default-backend-plugin/src/plugin.test.ts.hbs index cd4b9fc438..b6f387383e 100644 --- a/packages/cli/templates/default-backend-plugin/src/plugin.test.ts.hbs +++ b/packages/cli/templates/default-backend-plugin/src/plugin.test.ts.hbs @@ -9,7 +9,7 @@ import { catalogServiceMock } from '@backstage/plugin-catalog-node/testUtils'; // TEMPLATE NOTE: // Plugin tests are integration tests for your plugin, ensuring that all pieces // work together end-to-end. You can still mock injected backend services -// however, just like anyway that installs your plugin might replace the +// however, just like anyone who installs your plugin might replace the // services with their own implementations. describe('plugin', () => { it('should create and read TODO items', async () => { From 9a86d790173eed371b484398af2bc99e422207f1 Mon Sep 17 00:00:00 2001 From: Patrik Oldsberg Date: Sat, 12 Oct 2024 23:49:57 +0200 Subject: [PATCH 7/7] cli: update backend plugin templating test Signed-off-by: Patrik Oldsberg --- packages/cli/src/lib/new/factories/backendPlugin.test.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/cli/src/lib/new/factories/backendPlugin.test.ts b/packages/cli/src/lib/new/factories/backendPlugin.test.ts index c5dc237517..5415a3cd71 100644 --- a/packages/cli/src/lib/new/factories/backendPlugin.test.ts +++ b/packages/cli/src/lib/new/factories/backendPlugin.test.ts @@ -92,12 +92,16 @@ describe('backendPlugin factory', () => { 'templating .eslintrc.js.hbs', 'templating README.md.hbs', 'templating index.ts.hbs', + 'templating index.ts.hbs', 'templating package.json.hbs', + 'templating plugin.ts.hbs', + 'templating plugin.test.ts.hbs', 'copying index.ts', 'copying setupTests.ts', - 'copying router.test.ts', 'copying router.ts', - 'templating plugin.ts.hbs', + 'copying router.test.ts', + 'copying createTodoListService.ts', + 'copying types.ts', 'Installing:', `moving plugins${sep}test-backend`, 'backend adding dependency',