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

feat: add history versions endpoint #19386

Merged
merged 7 commits into from Feb 2, 2024
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
@@ -0,0 +1,83 @@
import { createHistoryVersionController } from '../history-version';

const mockFindVersionsPage = jest.fn();

// History utils
jest.mock('../../utils', () => ({
getService: jest.fn((_strapi, name) => {
if (name === 'history') {
return {
findVersionsPage: mockFindVersionsPage,
};
}
}),
}));

// Content Manager utils
jest.mock('../../../utils', () => ({
getService: jest.fn((name) => {
if (name === 'permission-checker') {
return {
create: jest.fn(() => ({
cannot: {
read: jest.fn(() => false),
},
})),
};
}
}),
}));

const mockStrapi = {};

// @ts-expect-error - we're not mocking the entire strapi object
const historyVersionController = createHistoryVersionController({ strapi: mockStrapi });

describe('History version controller', () => {
describe('findMany', () => {
it('should require contentType and documentId', () => {
const ctx = {
state: {
userAbility: {},
},
query: {},
};

// @ts-expect-error partial context
expect(historyVersionController.findMany(ctx)).rejects.toThrow(
/contentType and documentId are required/
);

expect(mockFindVersionsPage).not.toHaveBeenCalled();
});
});

it('should call findVersionsPage', async () => {
const ctx = {
state: {
userAbility: {},
},
query: {
documentId: 'document-id',
contentType: 'api::test.test',
},
};

mockFindVersionsPage.mockResolvedValueOnce({
results: [{ id: 'history-version-id' }],
pagination: {
page: 1,
pageSize: 10,
pageCount: 1,
total: 0,
},
});

// @ts-expect-error partial context
const response = await historyVersionController.findMany(ctx);

expect(mockFindVersionsPage).toHaveBeenCalled();
expect(response.data.length).toBe(1);
expect(response.meta.pagination).toBeDefined();
});
});
@@ -0,0 +1,36 @@
import { errors } from '@strapi/utils';
import type { Common, Strapi } from '@strapi/types';
import { getService as getContentManagerService } from '../../utils';
import { getService } from '../utils';
import { HistoryVersions } from '../../../../shared/contracts';

const createHistoryVersionController = ({ strapi }: { strapi: Strapi }) => {
return {
async findMany(ctx) {
if (!ctx.query.contentType || !ctx.query.documentId) {
throw new errors.ForbiddenError('contentType and documentId are required');
}

const params = ctx.query as HistoryVersions.GetHistoryVersions.Request['query'];

/**
* There are no permissions specifically for history versions,
* but we need to check that the user can read the content type
*/
const permissionChecker = getContentManagerService('permission-checker').create({
userAbility: ctx.state.userAbility,
model: params.contentType,
});

if (permissionChecker.cannot.read()) {
return ctx.forbidden();
}

const { results, pagination } = await getService(strapi, 'history').findVersionsPage(params);

return { data: results, meta: { pagination } };
},
} satisfies Common.Controller;
};

export { createHistoryVersionController };
@@ -1,7 +1,10 @@
import type { Plugin } from '@strapi/types';
import { createHistoryVersionController } from './history-version';

/**
* The controllers will me merged with the other Content Manager controllers,
* so we need to avoid conficts in the controller names.
*/
export const controllers: Plugin.LoadedPlugin['controllers'] = {};
export const controllers = {
'history-version': createHistoryVersionController,
/**
* Casting is needed because the types aren't aware that Strapi supports
* passing a controller factory as the value, instead of a controller object directly
*/
} as unknown as Plugin.LoadedPlugin['controllers'];
2 changes: 2 additions & 0 deletions packages/core/content-manager/server/src/history/index.ts
Expand Up @@ -2,6 +2,7 @@ import type { Plugin } from '@strapi/types';
import { controllers } from './controllers';
import { services } from './services';
import { contentTypes } from './content-types';
import { routes } from './routes';
import { getService } from './utils';

/**
Expand All @@ -19,6 +20,7 @@ const getFeature = (): Partial<Plugin.LoadedPlugin> => {
controllers,
services,
contentTypes,
routes,
};
}

Expand Down
@@ -0,0 +1,20 @@
import type { Plugin } from '@strapi/types';

const info = { pluginName: 'content-manager', type: 'admin' };

const historyVersionRouter: Plugin.LoadedPlugin['routes'][string] = {
type: 'admin',
routes: [
{
method: 'GET',
info,
path: '/history-versions',
handler: 'history-version.findMany',
config: {
policies: ['admin::isAuthenticatedAdmin'],
},
},
],
};

export { historyVersionRouter };
@@ -1,7 +1,10 @@
import type { Plugin } from '@strapi/types';
import { historyVersionRouter } from './history-version';

/**
* The routes will me merged with the other Content Manager routers,
* so we need to avoid conficts in the router name, and to prefix the path for each route.
*/
export const routes: Plugin.LoadedPlugin['routes'] = {};
export const routes = {
'history-version': historyVersionRouter,
} satisfies Plugin.LoadedPlugin['routes'];
Expand Up @@ -81,6 +81,34 @@ const createHistoryService = ({ strapi }: { strapi: LoadedStrapi }) => {
},
});
},

async findVersionsPage(params: HistoryVersions.GetHistoryVersions.Request['query']) {
const { results, pagination } = await query.findPage({
page: 1,
pageSize: 10,
where: {
$and: [
{ contentType: params.contentType },
{ relatedDocumentId: params.documentId },
{ locale: params.locale || null },
],
},
populate: ['createdBy'],
orderBy: [{ createdAt: 'desc' }],
});

const sanitizedResults = results.map((result) => ({
...result,
createdBy: result.createdBy
? strapi.admin.services.user.sanitizeUser(result.createdBy)
: null,
}));

return {
results: sanitizedResults,
pagination,
};
},
};
};

Expand Down
43 changes: 43 additions & 0 deletions packages/core/content-manager/shared/contracts/history-versions.ts
@@ -1,4 +1,5 @@
import type { Entity, UID } from '@strapi/types';
import { type errors } from '@strapi/utils';

/**
* Unlike other Content Manager contracts, history versions can't be created via
Expand All @@ -13,3 +14,45 @@ export interface CreateHistoryVersion {
data: Record<string, unknown>;
schema: Record<string, unknown>;
}

export interface HistoryVersionDataResponse extends CreateHistoryVersion {
id: Entity.ID;
createdAt: Date;
remidej marked this conversation as resolved.
Show resolved Hide resolved
createdBy: {
id: Entity.ID;
firstname: string;
lastname: string;
remidej marked this conversation as resolved.
Show resolved Hide resolved
username?: string;
};
remidej marked this conversation as resolved.
Show resolved Hide resolved
}

type Pagination = {
page: number;
pageSize: number;
pageCount: number;
total: number;
};

/**
* GET /content-manager/history-versions
*/
export declare namespace GetHistoryVersions {
export interface Request {
state: {
userAbility: {};
};
query: {
contentType: UID.ContentType;
documentId: Entity.ID;
locale?: string;
};
}

export interface Response {
data: HistoryVersionDataResponse[];
meta: {
pagination?: Pagination;
};
error?: errors.ApplicationError;
}
}