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(registry): templates/localized API #610

Merged
merged 15 commits into from
Oct 2, 2024
Merged
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
2 changes: 1 addition & 1 deletion registry/package.json
Original file line number Diff line number Diff line change
@@ -102,4 +102,4 @@
"node": "^20.8.0"
},
"engineStrict": true
}
}
46 changes: 46 additions & 0 deletions registry/server/middleware/validatelocales.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { Request, Response } from 'express';
import Joi from 'joi';

import { SettingKeys } from '../settings/interfaces';
import settingsService from '../settings/services/SettingsService';
import { getJoiErr, joiErrorToResponse } from '../util/helpers';

export const validateLocalesMiddleware =
(
localesFromRequest: (req: Request) => string[],
unsupportedLocalesToFieldName: (unsupportedLocales: string[]) => string,
) =>
async (req: Request, res: Response, next: () => void) => {
const locales = localesFromRequest(req);

if (locales.length === 0) {
next();
return;
}

const unsupportedLocales = await getUnsupportedLocales(locales);
if (unsupportedLocales.length > 0) {
res.status(422).send(
joiErrorToResponse(
unsupportedLocalesToJoiError(unsupportedLocales, unsupportedLocalesToFieldName(unsupportedLocales)),
),
);
return;
}

next();
};

async function getUnsupportedLocales(locales: string[]): Promise<string[]> {
const supportedLocales = await settingsService.get(SettingKeys.I18nSupportedLocales);
return locales.filter((l) => !supportedLocales.includes(l));
}

function unsupportedLocalesToJoiError(unsupportedLocales: string[], field: string): Joi.ValidationError {
return getJoiErr(
`localizedVersions.${unsupportedLocales[0]}`,
`Next locales are not supported ${unsupportedLocales.join(',')}. Either change request or change ${
SettingKeys.I18nSupportedLocales
} setting.`,
);
}
4 changes: 4 additions & 0 deletions registry/server/templates/errors.ts
Original file line number Diff line number Diff line change
@@ -3,4 +3,8 @@ import { extendError } from '../util/extendError';
export default {
FetchIncludeError: extendError('FetchIncludeError', { defaultData: {} }),
InvalidTemplateError: extendError('InvalidTemplateError', { defaultData: {} }),
TemplateNotFoundError: extendError('TemplateNotFoundError', {
defaultMessage: 'Template not found',
defaultData: {},
}),
};
16 changes: 15 additions & 1 deletion registry/server/templates/interfaces/index.ts
Original file line number Diff line number Diff line change
@@ -3,8 +3,22 @@ export default interface Template {
content: string;
}

export interface LocalizedTemplate {
export interface LocalizedTemplateRow {
templateName: string;
content: string;
locale: string;
}

export interface LocalizedVersion {
content: string;
}

export interface TemplateWithLocalizedVersions extends Template {
localizedVersions: Record<string, LocalizedVersion>;
}

export type UpdateTemplatePayload = Omit<Template, 'name' | 'localizedVersions'> &
Partial<Pick<TemplateWithLocalizedVersions, 'localizedVersions'>>;

export type CreateTemplatePayload = Omit<Template, 'localizedVersions'> &
Partial<Pick<TemplateWithLocalizedVersions, 'localizedVersions'>>;
51 changes: 10 additions & 41 deletions registry/server/templates/routes/createTemplate.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import { Request, Response } from 'express';

import db from '../../db';
import validateRequestFactory from '../../common/services/validateRequest';
import Template, { LocalizedTemplate } from '../interfaces';
import { Tables } from '../../db/structure';
import { templatesRepository } from '../services/templatesRepository';
import { templateSchema, validateLocalesAreSupported } from './validation';
import { templateSchema } from './validation';
import { validateLocalesMiddleware } from '../../middleware/validatelocales';

const validateRequestBeforeCreateTemplate = validateRequestFactory([
{
@@ -14,47 +12,18 @@ const validateRequestBeforeCreateTemplate = validateRequestFactory([
},
]);

const validateLocale = validateLocalesMiddleware(
(req) => Object.keys(req.body.localizedVersions ?? {}),
(unsupportedLocales) => `body.localizedVersions.${unsupportedLocales[0]}`,
);

const createTemplate = async (req: Request, res: Response): Promise<void> => {
try {
const request = req.body;
const template: Template = {
name: request.name,
content: request.content,
};

const locales = Object.keys(request.localizedVersions || {});
let localesAreValid = await validateLocalesAreSupported(locales, res);
if (!localesAreValid) {
return;
}

await db.versioning(req.user, { type: 'templates', id: template.name }, async (trx) => {
await db('templates').insert(template).transacting(trx);
});

if (locales.length > 0) {
await insertLocalizedVersions(locales, template, request);
}

const savedTemplate = await templatesRepository.readTemplateWithAllVersions(template.name);
res.status(200).send(savedTemplate);
const result = await templatesRepository.createTemplate(req.body, req.user);
res.status(200).send(result);
} catch (e) {
res.status(500).send(JSON.stringify(e));
}
};

function insertLocalizedVersions(locales: string[], template: Template, request: Record<string, any>) {
return Promise.all(
locales.map((locale) => {
const localizedTemplate: LocalizedTemplate = {
templateName: template.name,
content: request.localizedVersions[locale].content,
locale: locale,
};

return db(Tables.TemplatesLocalized).insert(localizedTemplate);
}),
);
}

export default [validateRequestBeforeCreateTemplate, createTemplate];
export default [validateRequestBeforeCreateTemplate, validateLocale, createTemplate];
44 changes: 44 additions & 0 deletions registry/server/templates/routes/deleteTemplateLocalizedVersion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { Request, Response } from 'express';
import Joi from 'joi';

import validateRequestFactory from '../../common/services/validateRequest';
import { exhaustiveCheck } from '../../util/exhaustiveCheck';
import { templatesRepository } from '../services/templatesRepository';
import { localeNameSchema, templateNameSchema } from './validation';

const validateRequestBeforeDeleteTemplateLocalizedVersion = validateRequestFactory([
{
schema: Joi.object({
name: templateNameSchema.required(),
locale: localeNameSchema.required(),
}),
selector: 'params',
},
]);

type Params = {
name: string;
locale: string;
};

const deleteTemplateLocalizedVersion = async (req: Request<Params>, res: Response): Promise<void> => {
const { name: templateName, locale } = req.params;

const result = await templatesRepository.deleteLocalizedVersion(templateName, locale);
switch (result.type) {
case 'notFound': {
res.status(404).send('Not found');
return;
}
case 'ok': {
res.status(204).send();
return;
}
default: {
/* istanbul ignore next */
exhaustiveCheck(result);
}
}
};

export default [validateRequestBeforeDeleteTemplateLocalizedVersion, deleteTemplateLocalizedVersion];
4 changes: 2 additions & 2 deletions registry/server/templates/routes/getRenderedTemplate.ts
Original file line number Diff line number Diff line change
@@ -3,7 +3,7 @@ import Joi from 'joi';

import noticeError from '../../errorHandler/noticeError';
import db from '../../db';
import Template, { LocalizedTemplate } from '../interfaces';
import Template, { LocalizedTemplateRow } from '../interfaces';
import validateRequestFactory from '../../common/services/validateRequest';
import renderTemplate from '../services/renderTemplate';
import errors from '../errors';
@@ -89,7 +89,7 @@ async function getRenderedTemplate(req: Request<GetTemplateRenderedRequestParams
if (locale) {
const [localizedTemplate] = await db
.select()
.from<LocalizedTemplate>(Tables.TemplatesLocalized)
.from<LocalizedTemplateRow>(Tables.TemplatesLocalized)
.where('templateName', templateName)
.andWhere('locale', locale as string);

4 changes: 4 additions & 0 deletions registry/server/templates/routes/index.ts
Original file line number Diff line number Diff line change
@@ -6,6 +6,8 @@ import getTemplates from './getTemplates';
import updateTemplate from './updateTemplate';
import createTemplate from './createTemplate';
import deleteTemplate from './deleteTemplate';
import upsertTemplateLocalizedVersion from './upsertTemplateLocalizedVersion';
import deleteTemplateLocalizedVersion from './deleteTemplateLocalizedVersion';

export default (authMw: RequestHandler[]) => {
const templatesRouter = express.Router();
@@ -16,6 +18,8 @@ export default (authMw: RequestHandler[]) => {
templatesRouter.get('/:name', ...getTemplate);
templatesRouter.put('/:name', authMw, ...updateTemplate);
templatesRouter.delete('/:name', authMw, ...deleteTemplate);
templatesRouter.put('/:name/localized/:locale', authMw, ...upsertTemplateLocalizedVersion);
templatesRouter.delete('/:name/localized/:locale', authMw, ...deleteTemplateLocalizedVersion);

return templatesRouter;
};
52 changes: 24 additions & 28 deletions registry/server/templates/routes/updateTemplate.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import { Request, Response } from 'express';
import Joi from 'joi';

import db from '../../db';
import validateRequestFactory from '../../common/services/validateRequest';
import { validateLocalesMiddleware } from '../../middleware/validatelocales';
import { exhaustiveCheck } from '../../util/exhaustiveCheck';
import { templatesRepository } from '../services/templatesRepository';
import { partialTemplateSchema, templateNameSchema, validateLocalesAreSupported } from './validation';
import { partialTemplateSchema, templateNameSchema } from './validation';

type UpdateTemplateRequestParams = {
name: string;
@@ -23,33 +24,28 @@ const validateRequestBeforeUpdateTemplate = validateRequestFactory([
},
]);

const updateTemplate = async (req: Request<UpdateTemplateRequestParams>, res: Response): Promise<void> => {
const template = {
content: req.body.content,
};
const templateName = req.params.name;

const templatesToUpdate = await db('templates').where({
name: templateName,
});
if (!templatesToUpdate.length) {
res.status(404).send('Not found');
return;
}
const validateLocale = validateLocalesMiddleware(
(req) => Object.keys(req.body.localizedVersions ?? {}),
(unsupportedLocales) => `body.localizedVersions.${unsupportedLocales[0]}`,
);

const localizedVersions = req.body.localizedVersions || {};
const localesAreValid = await validateLocalesAreSupported(Object.keys(localizedVersions), res);
if (!localesAreValid) {
return;
const updateTemplate = async (req: Request<UpdateTemplateRequestParams>, res: Response): Promise<void> => {
const result = await templatesRepository.updateTemplate(req.params.name, req.body, req.user);

switch (result.type) {
case 'notFound': {
res.status(404).send('Not found');
return;
}
case 'ok': {
res.status(200).send(result.template);
return;
}
default: {
/* istanbul ignore next */
exhaustiveCheck(result);
}
}

await db.versioning(req.user, { type: 'templates', id: templateName }, async (trx) => {
await db('templates').where({ name: templateName }).update(template).transacting(trx);
await templatesRepository.upsertLocalizedVersions(templateName, localizedVersions, trx);
});

const updatedTemplate = await templatesRepository.readTemplateWithAllVersions(templateName);
res.status(200).send(updatedTemplate);
};

export default [validateRequestBeforeUpdateTemplate, updateTemplate];
export default [validateRequestBeforeUpdateTemplate, validateLocale, updateTemplate];
59 changes: 59 additions & 0 deletions registry/server/templates/routes/upsertTemplateLocalizedVersion.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { Request, Response } from 'express';
import Joi from 'joi';

import validateRequestFactory from '../../common/services/validateRequest';
import { validateLocalesMiddleware } from '../../middleware/validatelocales';
import { exhaustiveCheck } from '../../util/exhaustiveCheck';
import { LocalizedVersion } from '../interfaces';
import { templatesRepository } from '../services/templatesRepository';
import { localeNameSchema, localizedVersionSchema, templateNameSchema } from './validation';

const validateRequestBeforeUpsertLocalizedVersion = validateRequestFactory([
{
schema: Joi.object({
name: templateNameSchema.required(),
locale: localeNameSchema.required(),
}),
selector: 'params',
},
{
schema: localizedVersionSchema.required(),
selector: 'body',
},
]);

const validateLocale = validateLocalesMiddleware(
(req) => [req.params.locale],
() => 'params.locale',
);

type Params = {
name: string;
locale: string;
};

const upsertTemplateLocalizedVersion = async (
req: Request<Params, any, LocalizedVersion>,
res: Response,
): Promise<void> => {
const { name: templateName, locale } = req.params;
const localizedVersion = req.body;

const result = await templatesRepository.upsertLocalizedVersion(templateName, locale, localizedVersion);
switch (result.type) {
case 'notFound': {
res.status(404).send('Not found');
return;
}
case 'ok': {
res.status(200).send(result.localizedVersion);
return;
}
default: {
/* istanbul ignore next */
exhaustiveCheck(result);
}
}
};

export default [validateRequestBeforeUpsertLocalizedVersion, validateLocale, upsertTemplateLocalizedVersion];
44 changes: 13 additions & 31 deletions registry/server/templates/routes/validation.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import Joi from 'joi';
import renderTemplate from '../services/renderTemplate';
import { getJoiErr, joiErrorToResponse } from '../../util/helpers';
import { Response } from 'express';
import settingsService from '../../settings/services/SettingsService';
import { SettingKeys } from '../../settings/interfaces';
import settingsService from '../../settings/services/SettingsService';
import { getJoiErr } from '../../util/helpers';
import renderTemplate from '../services/renderTemplate';

export const templateNameSchema = Joi.string().min(1).max(50);

@@ -24,15 +23,16 @@ const commonTemplate = {
versionId: Joi.string().strip(),
};

const localizedVersions = Joi.object().pattern(
Joi.string()
.regex(/[a-z]{2}-[A-Z]{2,4}/)
.min(5)
.max(7),
Joi.object({
content: commonTemplate.content.required(),
}),
);
export const localeNameSchema = Joi.string()
.regex(/[a-z]{2}-[A-Z]{2,4}/)
.min(5)
.max(7);

export const localizedVersionSchema = Joi.object({
content: commonTemplate.content.required(),
});

const localizedVersions = Joi.object().pattern(localeNameSchema, localizedVersionSchema);

export const partialTemplateSchema = Joi.object({
...commonTemplate,
@@ -46,21 +46,3 @@ export const templateSchema = Joi.object({
content: commonTemplate.content.required(),
localizedVersions,
});

export async function validateLocalesAreSupported(locales: string[], res: Response) {
const supportedLocales = await settingsService.get(SettingKeys.I18nSupportedLocales);
let unsupportedLocales = locales.filter((l) => !supportedLocales.includes(l));
if (unsupportedLocales.length > 0) {
let joiError = getJoiErr(
`localizedVersions.${unsupportedLocales[0]}`,
`Next locales are not supported ${unsupportedLocales.join(',')}. Either change request or change ${
SettingKeys.I18nSupportedLocales
} setting.`,
);
res.status(422);
res.send(joiErrorToResponse(joiError));
return false;
}

return true;
}
192 changes: 180 additions & 12 deletions registry/server/templates/services/templatesRepository.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,65 @@
import { ok } from 'assert';
import { Knex } from 'knex';

import { PaginatedResult } from '../../../typings/PaginatedResult';
import { User } from '../../../typings/User';
import db, { VersionedKnex } from '../../db';
import { Tables } from '../../db/structure';
import { appendDigest } from '../../util/hmac';
import { EntityTypes } from '../../versioning/interfaces';
import Template, { LocalizedTemplate } from '../interfaces';
import { normalizeArray } from '../../util/normalizeArray';
import { EntityTypes, VersionedRecord } from '../../versioning/interfaces';
import errors from '../errors';
import Template, {
CreateTemplatePayload,
LocalizedTemplateRow,
LocalizedVersion,
TemplateWithLocalizedVersions,
UpdateTemplatePayload,
} from '../interfaces';

import Transaction = Knex.Transaction;
import { normalizeArray } from '../../util/normalizeArray';

export interface TemplatesGetListFilters {
domainId?: number | 'null';
id?: string[] | string;
name?: string[] | string;
}

interface UpdateTemplateResultOk {
type: 'ok';
template: VersionedRecord<TemplateWithLocalizedVersions>;
}

interface UpdateTemplateResultNotFound {
type: 'notFound';
}

type UpdateTemplateResult = UpdateTemplateResultOk | UpdateTemplateResultNotFound;

interface UpsertTemplateLocalizedVersionResultOk {
type: 'ok';
localizedVersion: LocalizedVersion;
}

interface UpsertTemplateLocalizedVersionResultNotFound {
type: 'notFound';
}

type UpsertTemplateLocalizedVersionResult =
| UpsertTemplateLocalizedVersionResultOk
| UpsertTemplateLocalizedVersionResultNotFound;

interface DeleteTemplateLocalizedVersionResultOk {
type: 'ok';
}

interface DeleteTemplateLocalizedVersionResultNotFound {
type: 'notFound';
}

type DeleteTemplateLocalizedVersionResult =
| DeleteTemplateLocalizedVersionResultOk
| DeleteTemplateLocalizedVersionResultNotFound;

export class TemplatesRepository {
constructor(private db: VersionedKnex) {}

@@ -47,11 +90,15 @@ export class TemplatesRepository {
};
}

async readTemplateWithAllVersions(templateName: string) {
async readTemplateWithAllVersions(
templateName: string,
): Promise<VersionedRecord<TemplateWithLocalizedVersions> | undefined> {
const { db } = this;

const [template] = await db
.selectVersionedRowsFrom(Tables.Templates, 'name', EntityTypes.templates, [`${Tables.Templates}.*`])
.selectVersionedRowsFrom<Template>(Tables.Templates, 'name', EntityTypes.templates, [
`${Tables.Templates}.*`,
])
.where('name', templateName);

if (!template) {
@@ -60,22 +107,141 @@ export class TemplatesRepository {

template.versionId = appendDigest(template.versionId, 'template');

const localizedTemplates: LocalizedTemplate[] = await db
const localizedTemplates: LocalizedTemplateRow[] = await db
.select()
.from<LocalizedTemplate>(Tables.TemplatesLocalized)
.from<LocalizedTemplateRow>(Tables.TemplatesLocalized)
.where('templateName', templateName);
template.localizedVersions = localizedTemplates.reduce(

const localizedVersions = localizedTemplates.reduce(
(acc, item) => {
acc[item.locale] = { content: item.content };
return acc;
},
{} as Record<string, object>,
{} as Record<string, LocalizedVersion>,
);

return { ...template, localizedVersions };
}

async createTemplate(
template: CreateTemplatePayload,
user: User | undefined,
): Promise<VersionedRecord<TemplateWithLocalizedVersions>> {
const { db } = this;
const templateToCreate = {
name: template.name,
content: template.content,
};

const localizedVersions = template.localizedVersions ?? {};

await db.versioning(user, { type: EntityTypes.templates, id: template.name }, async (trx) => {
await db(Tables.Templates).insert(templateToCreate).transacting(trx);
if (Object.keys(localizedVersions).length > 0) {
await this.upsertLocalizedVersions(template.name, localizedVersions, trx);
}
});

const savedTemplate = await this.mustReadTemplateWithAllVersions(template.name);

return savedTemplate;
}

async updateTemplate(
templateName: string,
payload: UpdateTemplatePayload,
user: User | undefined,
): Promise<UpdateTemplateResult> {
const { db } = this;

const templatesToUpdate = await db(Tables.Templates).where({
name: templateName,
});
if (!templatesToUpdate.length) {
return { type: 'notFound' };
}
const localizedVersions = payload.localizedVersions ?? {};

await db.versioning(
user,
{
type: EntityTypes.templates,
id: templateName,
},
async (trx) => {
await db(Tables.Templates)
.where({ name: templateName })
.update({ content: payload.content })
.transacting(trx);
await this.upsertLocalizedVersions(templateName, localizedVersions, trx);
},
);

return template;
const updatedTemplate = await this.mustReadTemplateWithAllVersions(templateName);

return { type: 'ok', template: updatedTemplate };
}

async upsertLocalizedVersions(templateName: string, localizedVersions: any, trx: Transaction) {
async upsertLocalizedVersion(
templateName: string,
locale: string,
localizedVersion: LocalizedVersion,
): Promise<UpsertTemplateLocalizedVersionResult> {
const { db } = this;

const result = await db.transaction(async (trx): Promise<UpsertTemplateLocalizedVersionResult> => {
harnyk marked this conversation as resolved.
Show resolved Hide resolved
const existingTemplate = await trx(Tables.Templates).where({ name: templateName }).select(1).first();
if (!existingTemplate) {
return { type: 'notFound' };
}

const existingRecord = await trx(Tables.TemplatesLocalized)
.where({ templateName, locale })
.select(1)
.first();

if (existingRecord) {
await trx(Tables.TemplatesLocalized)
.update({ content: localizedVersion.content })
.where({ templateName, locale });
} else {
await trx(Tables.TemplatesLocalized).insert({
templateName,
locale,
content: localizedVersion.content,
});
}

return { type: 'ok', localizedVersion } as const;
});

return result;
}

async deleteLocalizedVersion(templateName: string, locale: string): Promise<DeleteTemplateLocalizedVersionResult> {
const { db } = this;
const result = await db(Tables.TemplatesLocalized).where({ templateName, locale }).delete();
if (result === 0) {
return { type: 'notFound' };
}
return { type: 'ok' };
}

private async mustReadTemplateWithAllVersions(
templateName: string,
): Promise<VersionedRecord<TemplateWithLocalizedVersions>> {
const maybeTemplate = await this.readTemplateWithAllVersions(templateName);
if (!maybeTemplate) {
throw new errors.TemplateNotFoundError({ data: { templateName } });
}
return maybeTemplate;
}

private async upsertLocalizedVersions(
templateName: string,
localizedVersions: Record<string, LocalizedVersion>,
trx: Transaction,
): Promise<void> {
const { db } = this;

const locales = Object.keys(localizedVersions);
@@ -119,6 +285,8 @@ export class TemplatesRepository {
}

private addFilterByDomainId(query: Knex.QueryBuilder, filters: TemplatesGetListFilters) {
const { db } = this;

if (!filters.domainId) {
return;
}
3 changes: 3 additions & 0 deletions registry/server/util/exhaustiveCheck.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function exhaustiveCheck(value: never): never {
throw new Error(`Unexpected value: ${value}`);
}
118 changes: 118 additions & 0 deletions registry/tests/templates.spec.ts
Original file line number Diff line number Diff line change
@@ -514,6 +514,23 @@ describe(`Tests ${example.url}`, () => {
.expect(422, 'HTML template has invalid structure');
});

it('should not update record with unsupported locale', async () => {
await req.post(example.url).send(example.correct).expect(200);

await req
.put(example.url + example.correct.name)
.send({
content: example.correct.content,
localizedVersions: {
'zh-CN': { content: example.correct.content },
},
})
.expect(
422,
'Next locales are not supported zh-CN. Either change request or change i18n.supported.locale setting.',
);
});

it('should successfully update record', async () => {
await req.post(example.url).send(example.correct).expect(200);

@@ -771,4 +788,105 @@ describe(`Tests ${example.url}`, () => {
}
});
});

describe('Localized', () => {
describe('Create', () => {
it('should not allow to create localized template version for unsupported locale', async () => {
try {
await req.post(example.url).send(example.correct).expect(200);

await req
.put(example.url + example.correct.name + '/localized/pt-BR')
.send({ content: example.correct.content })
.expect(422);
} finally {
await req.delete(example.url + example.correct.name).expect(204);
}
});

it('should not allow to create localized template version for a non-existent template', async () => {
const nonExistentTemplate = 'non-existent-template';

await req
.put(example.url + nonExistentTemplate + '/localized/ua-UA')
.send({ content: example.correct.content })
.expect(404);
});

it('should create localized template version', async () => {
try {
await req.post(example.url).send(example.correct).expect(200);

const response = await req
.put(example.url + example.correct.name + '/localized/ua-UA')
.send({ content: example.correct.content })
.expect(200);

expect(response.body).deep.equal({
content: example.correct.content,
});
} finally {
await req.delete(example.url + example.correct.name).expect(204);
harnyk marked this conversation as resolved.
Show resolved Hide resolved
}
});
});

describe('Update', () => {
it('should update localized template version', async () => {
try {
await req.post(example.url).send(example.correct).expect(200);
await req
.put(example.url + example.correct.name + '/localized/ua-UA')
.send({ content: example.correct.content })
.expect(200);
const response = await req
.put(example.url + example.correct.name + '/localized/ua-UA')
.send({ content: example.updated.content })
.expect(200);
harnyk marked this conversation as resolved.
Show resolved Hide resolved
expect(response.body).deep.equal({
content: example.updated.content,
});
} finally {
await req.delete(example.url + example.correct.name).expect(204);
}
});
});

describe('Delete', () => {
it('should not allow to delete localized template version for a non-existent template', async () => {
const nonExistentTemplate = 'non-existent-template';

await req
.put(example.url + nonExistentTemplate + '/localized/ua-UA')
.send({ content: example.correct.content })
.expect(404);
});

it('should not allow to delete a non-existent localized template version', async () => {
try {
await req.post(example.url).send(example.correct).expect(200);
await req
.put(example.url + example.correct.name + '/localized/ua-UA')
.send({ content: example.correct.content })
.expect(200);
await req.delete(example.url + example.correct.name + '/localized/en-US').expect(404);
} finally {
await req.delete(example.url + example.correct.name).expect(204);
}
});

it('should delete localized template version', async () => {
try {
await req.post(example.url).send(example.correct).expect(200);
await req
.put(example.url + example.correct.name + '/localized/ua-UA')
.send({ content: example.correct.content })
.expect(200);
await req.delete(example.url + example.correct.name + '/localized/ua-UA').expect(204);
} finally {
await req.delete(example.url + example.correct.name).expect(204);
}
});
});
});
});