Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Original file line number Diff line number Diff line change
Expand Up @@ -1489,7 +1489,7 @@ public async Task<PagedModel<TItem>> GetAllAllowedAsRootAsync(int skip, int take
TItem[] allowedChildren = GetMany(sortedKeys).ToArray();
result = new PagedModel<TItem>
{
Items = allowedChildren.OrderBy(x => sortedKeys.IndexOf(x.Key)).Take(take).Skip(skip),
Items = allowedChildren.OrderBy(x => sortedKeys.IndexOf(x.Key)).Skip(skip).Take(take),
Total = allowedChildren.Length,
};
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
const { http, HttpResponse } = window.MockServiceWorker;
import { umbDocumentTypeMockDb } from '../../db/document-type.db.js';
import { UMB_SLUG } from './slug.js';
import { pageResponse } from '../../utils.js';
import { umbracoPath } from '@umbraco-cms/backoffice/utils';

export const structureHandlers = [
http.get(umbracoPath(`${UMB_SLUG}/:id/allowed-children`), ({ params }) => {
http.get(umbracoPath(`${UMB_SLUG}/:id/allowed-children`), ({ params, request }) => {
const id = params.id as string;
if (!id) return new HttpResponse(null, { status: 400 });
const response = umbDocumentTypeMockDb.getAllowedChildren(id);
return HttpResponse.json(response);
return HttpResponse.json(pageResponse(response, request));
}),

http.get(umbracoPath(`${UMB_SLUG}/allowed-at-root`), () => {
http.get(umbracoPath(`${UMB_SLUG}/allowed-at-root`), ({ request }) => {
const response = umbDocumentTypeMockDb.getAllowedAtRoot();
return HttpResponse.json(response);
return HttpResponse.json(pageResponse(response, request));
}),

http.get(umbracoPath(`${UMB_SLUG}/:id/allowed-parents`), ({ params }) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
const { http, HttpResponse } = window.MockServiceWorker;
import { umbMediaTypeMockDb } from '../../db/media-type.db.js';
import { UMB_SLUG } from './slug.js';
import { pageResponse } from '../../utils.js';
import { umbracoPath } from '@umbraco-cms/backoffice/utils';

export const itemHandlers = [
Expand Down Expand Up @@ -43,6 +44,6 @@ export const itemHandlers = [

const response = umbMediaTypeMockDb.getAllowedByFileExtension(fileExtension);

return HttpResponse.json(response);
return HttpResponse.json(pageResponse(response, request));
}),
];
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
const { http, HttpResponse } = window.MockServiceWorker;
import { umbMediaTypeMockDb } from '../../db/media-type.db.js';
import { UMB_SLUG } from './slug.js';
import { pageResponse } from '../../utils.js';
import { umbracoPath } from '@umbraco-cms/backoffice/utils';

export const structureHandlers = [
http.get(umbracoPath(`${UMB_SLUG}/:id/allowed-children`), ({ params }) => {
http.get(umbracoPath(`${UMB_SLUG}/:id/allowed-children`), ({ params, request }) => {
const id = params.id as string;
if (!id) return new HttpResponse(null, { status: 400 });
const response = umbMediaTypeMockDb.getAllowedChildren(id);
return HttpResponse.json(response);
return HttpResponse.json(pageResponse(response, request));
}),

http.get(umbracoPath(`${UMB_SLUG}/allowed-at-root`), () => {
http.get(umbracoPath(`${UMB_SLUG}/allowed-at-root`), ({ request }) => {
const response = umbMediaTypeMockDb.getAllowedAtRoot();
return HttpResponse.json(response);
return HttpResponse.json(pageResponse(response, request));
}),

http.get(umbracoPath(`${UMB_SLUG}/:id/allowed-parents`), ({ params }) => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
const { http, HttpResponse } = window.MockServiceWorker;
import { umbMemberTypeMockDb } from '../../db/member-type.db.js';
import { UMB_SLUG } from './slug.js';
import { pageResponse } from '../../utils.js';
import { umbracoPath } from '@umbraco-cms/backoffice/utils';

export const structureHandlers = [
http.get(umbracoPath(`${UMB_SLUG}/allowed-at-root`), () => {
http.get(umbracoPath(`${UMB_SLUG}/allowed-at-root`), ({ request }) => {
const response = umbMemberTypeMockDb.getAllowedAtRoot();
return HttpResponse.json(response);
return HttpResponse.json(pageResponse(response, request));
}),
];
18 changes: 18 additions & 0 deletions src/Umbraco.Web.UI.Client/mocks/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,3 +50,21 @@ export function createProblemDetails(problemDetails: {
}): object {
return problemDetails;
}

/**
* Applies the `skip` and `take` query parameters of a request to an already-collected paged response, so a mocked
* endpoint pages like the real one does. `total` remains the full count.
* @param {object} response The full set of items, with their total.
* @param {Request} request The intercepted request to read `skip` and `take` from.
* @returns {object} The requested page of items, with the unchanged total.
*/
export function pageResponse<ItemType>(
response: { items: Array<ItemType>; total: number },
request: Request,
): { items: Array<ItemType>; total: number } {
const url = new URL(request.url);
const skip = Number(url.searchParams.get('skip')) || 0;
const take = Number(url.searchParams.get('take')) || 100;
Comment thread
AndyButland marked this conversation as resolved.
Resolved

return { items: response.items.slice(skip, skip + take), total: response.total };
}
Original file line number Diff line number Diff line change
@@ -1,15 +1,25 @@
import type { UmbControllerHost } from '@umbraco-cms/backoffice/controller-api';
import type { UmbEntityModel } from '@umbraco-cms/backoffice/entity';
import type { UmbDataSourceResponse, UmbPagedModel } from '@umbraco-cms/backoffice/repository';
import type { UmbOffsetPaginationRequestModel } from '@umbraco-cms/backoffice/utils';

export interface UmbContentTypeStructureDataSourceConstructor<ItemType> {
new (host: UmbControllerHost): UmbContentTypeStructureDataSource<ItemType>;
}

export interface UmbContentTypeStructureDataSource<ItemType> {
/**
* Returns a single page of the content types allowed as children.
* @param {string | null} unique - The content type to get the allowed children of, or `null` for the root.
* @param {string | null} parentContentUnique - The content item the children will be created under, if any.
* @param {UmbOffsetPaginationRequestModel} paging - The page to return. Implementations must honour this, as a
* source that ignores it returns the same page repeatedly when a caller pages through the full set.
* @returns {Promise} A promise resolving to `{ data: { items, total } }`, or `{ error }`.
*/
getAllowedChildrenOf(
unique: string | null,
parentContentUnique: string | null,
paging?: UmbOffsetPaginationRequestModel,
): Promise<UmbDataSourceResponse<UmbPagedModel<ItemType>>>;
getAllowedParentsOf?(unique: string): Promise<UmbDataSourceResponse<Array<UmbEntityModel>>>;
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,12 @@ import type {
UmbContentTypeStructureDataSource,
UmbContentTypeStructureDataSourceConstructor,
} from './content-type-structure-data-source.interface.js';
import { UmbRepositoryBase } from '@umbraco-cms/backoffice/repository';
import { fetchAllPages, UmbRepositoryBase } from '@umbraco-cms/backoffice/repository';
import type { UmbControllerHost } from '@umbraco-cms/backoffice/controller-api';
import type { UmbOffsetPaginationRequestModel } from '@umbraco-cms/backoffice/utils';

// Mirrors the server's default `take` for the allowed-children and allowed-at-root endpoints.
const ALLOWED_CHILDREN_PAGE_SIZE = 100;

export abstract class UmbContentTypeStructureRepositoryBase<ItemType>
extends UmbRepositoryBase
Expand All @@ -18,13 +22,34 @@ export abstract class UmbContentTypeStructureRepositoryBase<ItemType>
}

/**
* Returns a promise with the allowed children of a content type
* @param {string} unique
* @param parentContentUnique
* @returns {*}
* Returns a promise with a single page of the allowed children of a content type. The server returns the
* first 100 when no paging is given, so prefer `requestAllAllowedChildrenOf` when every allowed child is needed.
* @param {string | null} unique - The content type to get the allowed children of, or `null` for the root.
* @param {string | null} parentContentUnique - The content item the children will be created under, if any.
* @param {UmbOffsetPaginationRequestModel} paging - The page to return.
* @returns {Promise} A promise resolving to `{ data: { items, total } }`, or `{ error }`.
* @memberof UmbContentTypeStructureRepositoryBase
*/
requestAllowedChildrenOf(
unique: string | null,
parentContentUnique: string | null,
paging?: UmbOffsetPaginationRequestModel,
) {
return this._dataSource.getAllowedChildrenOf(unique, parentContentUnique, paging);
}

/**
* Returns a promise with every allowed child of a content type, by paging through the data source until all
* items have been retrieved.
* @param {string | null} unique - The content type to get the allowed children of, or `null` for the root.
* @param {string | null} parentContentUnique - The content item the children will be created under, if any.
* @returns {Promise} A promise resolving to `{ data: { items, total } }` containing every allowed child, or `{ error }`.
* @memberof UmbContentTypeStructureRepositoryBase
*/
requestAllowedChildrenOf(unique: string | null, parentContentUnique: string | null) {
return this._dataSource.getAllowedChildrenOf(unique, parentContentUnique);
requestAllAllowedChildrenOf(unique: string | null, parentContentUnique: string | null) {
return fetchAllPages<ItemType>(
(skip, take) => this._dataSource.getAllowedChildrenOf(unique, parentContentUnique, { skip, take }),
ALLOWED_CHILDREN_PAGE_SIZE,
);
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,23 @@
import type { UmbDataSourceResponse, UmbPagedModel } from '@umbraco-cms/backoffice/repository';
import type { UmbEntityModel } from '@umbraco-cms/backoffice/entity';
import type { UmbOffsetPaginationRequestModel } from '@umbraco-cms/backoffice/utils';

export interface UmbContentTypeStructureRepository<ItemType> {
/**
* Returns a single page of the content types allowed as children. The server returns the first 100 when
* no paging is given, so use `requestAllAllowedChildrenOf` when every allowed child is needed.
*/
requestAllowedChildrenOf(
unique: string,
unique: string | null,
parentContentUnique: string | null,
paging?: UmbOffsetPaginationRequestModel,
): Promise<UmbDataSourceResponse<UmbPagedModel<ItemType>>>;

/**
* Returns every content type allowed as a child, paging through the data source until all have been retrieved.
*/
requestAllAllowedChildrenOf?(
unique: string | null,
parentContentUnique: string | null,
): Promise<UmbDataSourceResponse<UmbPagedModel<ItemType>>>;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { UmbEntityModel } from '@umbraco-cms/backoffice/entity';
import type { UmbControllerHost } from '@umbraco-cms/backoffice/controller-api';
import { tryExecute } from '@umbraco-cms/backoffice/resources';
import type { UmbPagedModel, UmbDataSourceResponse } from '@umbraco-cms/backoffice/repository';
import type { UmbOffsetPaginationRequestModel } from '@umbraco-cms/backoffice/utils';

// Keep this type internal
type AllowedContentTypeBaseModel = {
Expand All @@ -19,6 +20,7 @@ export interface UmbContentTypeStructureServerDataSourceBaseArgs<
getAllowedChildrenOf: (
unique: string | null,
parentContentUnique: string | null,
paging?: UmbOffsetPaginationRequestModel,
) => Promise<UmbDataSourceResponse<UmbPagedModel<ServerItemType>>>;
mapper: (item: ServerItemType) => ClientItemType;
}
Expand Down Expand Up @@ -48,14 +50,22 @@ export abstract class UmbContentTypeStructureServerDataSourceBase<
}

/**
* Returns a promise with the allowed content types for the given unique
* @param {string} unique
* @param parentContentUnique
* Returns a promise with a single page of the allowed content types for the given unique
* @param {string | null} unique - The content type to get the allowed children of, or `null` for the root.
* @param {string | null} parentContentUnique - The content item the children will be created under, if any.
* @param {UmbOffsetPaginationRequestModel} paging - The page to return.
* @returns {*}
* @memberof UmbContentTypeStructureServerDataSourceBase
*/
async getAllowedChildrenOf(unique: string | null, parentContentUnique: string | null) {
const { data, error } = await tryExecute(this.#host, this.#getAllowedChildrenOf(unique, parentContentUnique));
async getAllowedChildrenOf(
unique: string | null,
parentContentUnique: string | null,
paging?: UmbOffsetPaginationRequestModel,
) {
const { data, error } = await tryExecute(
this.#host,
this.#getAllowedChildrenOf(unique, parentContentUnique, paging),
);

if (data) {
const items = data.items.map((item) => this.#mapper(item));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,120 @@
import { useMockHandlers, resetMockHandlers } from '../../../../../../mocks/index.js';
import { UmbDocumentTypeStructureRepository } from './document-type-structure.repository.js';
import { expect } from '@open-wc/testing';
import { customElement } from '@umbraco-cms/backoffice/external/lit';
import { UmbControllerHostElementMixin } from '@umbraco-cms/backoffice/controller-api';
import { umbracoPath } from '@umbraco-cms/backoffice/utils';

const { http, HttpResponse } = window.MockServiceWorker;

const UMB_SLUG = '/document-type';

const TOTAL_ITEMS = 150;

const allItems = Array.from({ length: TOTAL_ITEMS }, (_, index) => ({
id: `document-type-${index}`,
name: `Document Type ${index}`,
description: null,
icon: 'icon-document',
}));

type PageRequest = { skip: string | null; take: string | null };

@customElement('umb-test-document-type-structure-repository-host')
class UmbTestDocumentTypeStructureRepositoryHostElement extends UmbControllerHostElementMixin(HTMLElement) {}

describe('UmbDocumentTypeStructureRepository', () => {
let host: UmbTestDocumentTypeStructureRepositoryHostElement;
let repository: UmbDocumentTypeStructureRepository;
let requests: Array<PageRequest>;

// The global mock handlers ignore skip/take and always return everything, which would let an unpaged
// repository pass. These handlers page for real, so the assertions below only hold if the repository pages.
const pagingHandler = (path: string) =>
http.get(umbracoPath(path), ({ request }) => {
const url = new URL(request.url);
const skip = url.searchParams.get('skip');
const take = url.searchParams.get('take');
requests.push({ skip, take });

const from = Number(skip) || 0;
const size = take === null ? 100 : Number(take);

return HttpResponse.json({ items: allItems.slice(from, from + size), total: allItems.length });
});

beforeEach(() => {
requests = [];
host = new UmbTestDocumentTypeStructureRepositoryHostElement();
document.body.appendChild(host);
repository = new UmbDocumentTypeStructureRepository(host);
});

afterEach(() => {
repository.destroy();
document.body.innerHTML = '';
resetMockHandlers();
});

describe('requestAllAllowedChildrenOf', () => {
it('pages through every allowed child of a document type', async () => {
useMockHandlers(pagingHandler(`${UMB_SLUG}/:id/allowed-children`));

const { data } = await repository.requestAllAllowedChildrenOf('parent-document-type', null);

expect(data?.items).to.have.lengthOf(TOTAL_ITEMS);
expect(data?.total).to.equal(TOTAL_ITEMS);
expect(requests).to.eql([
{ skip: '0', take: '100' },
{ skip: '100', take: '100' },
]);
});

Check warning on line 71 in src/Umbraco.Web.UI.Client/src/packages/documents/document-types/repository/structure/document-type-structure.repository.test.ts

View check run for this annotation

CodeScene Delta Analysis / CodeScene Code Health Review (v17/dev)

❌ New issue: Code Duplication

The module contains 2 functions with similar structure: 'pages through every allowed child of a document type','pages through every document type allowed at root' Avoid duplicated, aka copy-pasted, code inside the module. More duplication lowers the code health.

it('pages through every document type allowed at root', async () => {
useMockHandlers(pagingHandler(`${UMB_SLUG}/allowed-at-root`));

const { data } = await repository.requestAllAllowedChildrenOf(null, null);

expect(data?.items).to.have.lengthOf(TOTAL_ITEMS);
expect(requests).to.eql([
{ skip: '0', take: '100' },
{ skip: '100', take: '100' },
]);
});

it('returns an error when a page fails', async () => {

Check failure on line 85 in src/Umbraco.Web.UI.Client/src/packages/documents/document-types/repository/structure/document-type-structure.repository.test.ts

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Add at least one assertion to this test case.

See more on https://sonarcloud.io/project/issues?id=umbraco_Umbraco-CMS&issues=AZ-31mLXnB25CsgH4hcE&open=AZ-31mLXnB25CsgH4hcE&pullRequest=23522
useMockHandlers(
http.get(umbracoPath(`${UMB_SLUG}/:id/allowed-children`), () => new HttpResponse(null, { status: 500 })),
);

const { data, error } = await repository.requestAllAllowedChildrenOf('parent-document-type', null);

expect(error).to.exist;
expect(data).to.be.undefined;
});
});

describe('requestAllowedChildrenOf', () => {
it('makes a single unpaged request when no paging is given', async () => {
useMockHandlers(pagingHandler(`${UMB_SLUG}/:id/allowed-children`));

const { data } = await repository.requestAllowedChildrenOf('parent-document-type', null);

expect(requests).to.eql([{ skip: null, take: null }]);
expect(data?.total).to.equal(TOTAL_ITEMS);
});

it('requests only the given page', async () => {
useMockHandlers(pagingHandler(`${UMB_SLUG}/:id/allowed-children`));

const { data } = await repository.requestAllowedChildrenOf('parent-document-type', null, {
skip: 100,
take: 100,
});

expect(requests).to.eql([{ skip: '100', take: '100' }]);
expect(data?.items).to.have.lengthOf(TOTAL_ITEMS - 100);
expect(data?.total).to.equal(TOTAL_ITEMS);
});
});
});
Loading
Loading