Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Experimental] Generate CRUD REST APIs for plugins using Content Management #187167

Closed
wants to merge 18 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -210,6 +210,7 @@
"@kbn/config-mocks": "link:packages/kbn-config-mocks",
"@kbn/config-schema": "link:packages/kbn-config-schema",
"@kbn/console-plugin": "link:src/plugins/console",
"@kbn/content-management-api": "link:packages/kbn-content-management-api",
"@kbn/content-management-content-editor": "link:packages/content-management/content_editor",
"@kbn/content-management-examples-plugin": "link:examples/content_management_examples",
"@kbn/content-management-plugin": "link:src/plugins/content_management",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import type { CoreVersionedRouter } from './core_versioned_router';

import { validate } from './validate';
import {
isAllowedPublicVersion,
isValidRouteVersion,
hasQueryVersion,
readVersion,
Expand Down Expand Up @@ -220,12 +219,12 @@ export class CoreVersionedRoute implements VersionedRoute {
private validateVersion(version: string) {
// We do an additional check here while we only have a single allowed public version
// for all public Kibana HTTP APIs
if (this.router.isDev && this.isPublic) {
const message = isAllowedPublicVersion(version);
if (message) {
throw new Error(message);
}
}
// if (this.router.isDev && this.isPublic) {
// const message = isAllowedPublicVersion(version);
// if (message) {
// throw new Error(message);
// }
// }

const message = isValidRouteVersion(this.isPublic, version);
if (message) {
Expand Down
4 changes: 4 additions & 0 deletions packages/kbn-content-management-api/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Content management API factory

Utilities to easily create APIs for CRUD operations.

10 changes: 10 additions & 0 deletions packages/kbn-content-management-api/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

export { registerAPIRoutes } from './src/register_routes';
export { contentManagementApiVersions } from './src/constants';
13 changes: 13 additions & 0 deletions packages/kbn-content-management-api/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

module.exports = {
preset: '@kbn/test',
rootDir: '../..',
roots: ['<rootDir>/packages/kbn-content-management-api'],
};
5 changes: 5 additions & 0 deletions packages/kbn-content-management-api/kibana.jsonc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"type": "shared-common",
"id": "@kbn/content-management-api",
"owner": "@elastic/kibana-presentation"
}
35 changes: 35 additions & 0 deletions packages/kbn-content-management-api/src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { schema } from '@kbn/config-schema';

export const contentManagementApiVersions = {
'2023-10-31': '2023-10-31',
} as const;

export const baseGetSchema = schema.object({
id: schema.string(),
type: schema.string(),
references: schema.arrayOf(
schema.object({
name: schema.string(),
type: schema.string(),
id: schema.string(),
}),
{ defaultValue: [] }
),
namespaces: schema.maybe(schema.arrayOf(schema.string())),
updatedAt: schema.maybe(schema.string()),
updatedBy: schema.maybe(schema.string()),
error: schema.maybe(schema.string()),
createdAt: schema.maybe(schema.string()),
createdBy: schema.maybe(schema.string()),
managed: schema.maybe(schema.boolean()),
version: schema.maybe(schema.string()),
attributes: schema.maybe(schema.any()),
});
244 changes: 244 additions & 0 deletions packages/kbn-content-management-api/src/register_routes.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { ObjectType, Props, schema } from '@kbn/config-schema';
import { type ContentManagementServerSetup } from '@kbn/content-management-plugin/server';
import { VersionedRouteResponseValidation } from '@kbn/core-http-server';
import { HttpServiceSetup } from '@kbn/core/server';
import { type UsageCounter } from '@kbn/usage-collection-plugin/server';
import { baseGetSchema, contentManagementApiVersions } from './constants';
import { ContentManagementApiVersionsType } from './types';

interface RegisterAPIRoutesArgs<P extends Props> {
http: HttpServiceSetup;
contentManagement: ContentManagementServerSetup;
appName: string;
contentId: string;
getSchemas: () => Record<
ContentManagementApiVersionsType,
{ schema: ObjectType<P>; validation?: VersionedRouteResponseValidation }
>;
getTransforms: () => Record<
ContentManagementApiVersionsType,
{ inTransform?: (data: unknown) => unknown; outTransform?: (data: unknown) => unknown }
>;
restCounter?: UsageCounter;
}

function recursiveSortObjectByKeys(obj: unknown): unknown {
if (typeof obj !== 'object' || obj === null) return obj;
if (Array.isArray(obj)) {
return obj.map(recursiveSortObjectByKeys);
}
return Object.keys(obj)
.sort()
.reduce((acc, key) => {
acc[key] = recursiveSortObjectByKeys(obj[key]);
return acc;
}, {} as Record<string, unknown>);
}

export function registerAPIRoutes<P extends Props>({
http,
contentManagement,
appName,
contentId,
getSchemas,
getTransforms,
restCounter,
}: RegisterAPIRoutesArgs<P>) {
const { versioned: versionedRouter } = http.createRouter();

// TODO add usage collection

// TODO add authorization checks

// Create API route
const createRoute = versionedRouter.post({
path: `/api/${appName}/${contentId}/{id?}`,
access: 'public',
description: `Create an item of type ${contentId}.`,
});

for (const version of Object.values(contentManagementApiVersions)) {
createRoute.addVersion(
{
version,
validate: {
request: {
params: schema.object({
id: schema.maybe(schema.string()),
}),
query: schema.object({
overwrite: schema.boolean({ defaultValue: false }),
}),
body: getSchemas()[version].schema,
},
response: {
200: {
body: () =>
baseGetSchema.extends({
attributes: getSchemas()[version].schema,
}),
},
},
},
},
async (ctx, req, res) => {
const { id } = req.params;
const { overwrite } = req.query;
const client = contentManagement.contentClient
.getForRequest({ request: req, requestHandlerContext: ctx })
.for(contentId);
let result;
try {
({
result: { item: result },
} = await client.create(req.body, { id, overwrite }));
} catch (e) {
// TODO do some error handling
throw e;
}

const body = recursiveSortObjectByKeys(result);
return res.ok({ body });
}
);
}

// Update API route

const updateRoute = versionedRouter.put({
path: `/api/${appName}/${contentId}/{id}`,
access: 'public',
description: `Update an item of type ${contentId}.`,
});

for (const version of Object.values(contentManagementApiVersions)) {
updateRoute.addVersion(
{
version,
validate: {
request: {
params: schema.object({
id: schema.string(),
}),
body: getSchemas()[version].schema,
},
response: {
200: {
body: () =>
baseGetSchema.extends({
attributes: getSchemas()[version].schema,
}),
},
},
},
},
async (ctx, req, res) => {
const client = contentManagement.contentClient
.getForRequest({ request: req, requestHandlerContext: ctx })
.for(contentId);
let result;
try {
({
result: { item: result },
} = await client.update(req.params.id, req.body));
} catch (e) {
// TODO do some error handling
throw e;
}

const body = recursiveSortObjectByKeys(result);
return res.ok({ body });
}
);
}

// Get API route
const getRoute = versionedRouter.get({
path: `/api/${appName}/${contentId}/{id}`,
access: 'public',
description: `Get an item of type ${contentId}.`,
});

for (const version of Object.values(contentManagementApiVersions)) {
getRoute.addVersion(
{
version,
validate: {
request: {
params: schema.object({
id: schema.string(),
}),
},
response: {
200: {
body: () =>
baseGetSchema.extends({
attributes: getSchemas()[version].schema,
}),
},
},
},
},
async (ctx, req, res) => {
const client = contentManagement.contentClient
.getForRequest({ request: req, requestHandlerContext: ctx })
.for(contentId);
let result;
try {
({
result: { item: result },
} = await client.get(req.params.id));
} catch (e) {
// TODO do some error handling
throw e;
}

const body = recursiveSortObjectByKeys(result);
return res.ok({ body });
}
);
}

// Delete API route
const deleteRoute = versionedRouter.delete({
path: `/api/${appName}/${contentId}/{id}`,
access: 'public',
description: `Delete an item of type ${contentId}.`,
});

for (const version of Object.values(contentManagementApiVersions)) {
deleteRoute.addVersion(
{
version,
validate: {
request: {
params: schema.object({
id: schema.string(),
}),
},
},
},
async (ctx, req, res) => {
const client = contentManagement.contentClient
.getForRequest({ request: req, requestHandlerContext: ctx })
.for(contentId);
try {
await client.delete(req.params.id);
} catch (e) {
// TODO do some error handling
throw e;
}

return res.ok();
}
);
}
}
12 changes: 12 additions & 0 deletions packages/kbn-content-management-api/src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/*
* Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
* or more contributor license agreements. Licensed under the Elastic License
* 2.0 and the Server Side Public License, v 1; you may not use this file except
* in compliance with, at your election, the Elastic License 2.0 or the Server
* Side Public License, v 1.
*/

import { contentManagementApiVersions } from './constants';

export type ContentManagementApiVersionsType =
typeof contentManagementApiVersions[keyof typeof contentManagementApiVersions];
28 changes: 28 additions & 0 deletions packages/kbn-content-management-api/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"outDir": "target/types",
"types": [
"jest",
"node",
"react"
]
},
"include": [
"**/*.ts",
"**/*.tsx",
],
"exclude": [
"target/**/*"
],
"kbn_references": [
"@kbn/content-management-plugin",
"@kbn/config-schema",
"@kbn/core-saved-objects-api-server",
"@kbn/config-schema",
"@kbn/object-versioning",
"@kbn/logging",
"@kbn/logging-mocks",
"@kbn/core",
]
}
Loading