Skip to content

Commit

Permalink
feat(backend): improve create organization errors typings
Browse files Browse the repository at this point in the history
  • Loading branch information
Mati365 committed Sep 28, 2024
1 parent 2447749 commit f5d689f
Show file tree
Hide file tree
Showing 11 changed files with 91 additions and 21 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,12 @@ import {
import { ConfigService } from '~/modules/config';
import { OrganizationsService } from '~/modules/organizations';

import { rejectUnsafeSdkErrors, sdkSchemaValidator, serializeSdkResponseTE } from '../helpers';
import {
rejectUnsafeCreateSdkErrors,
rejectUnsafeSdkErrors,
sdkSchemaValidator,
serializeSdkResponseTE,
} from '../helpers';
import { AuthorizedController } from './shared/authorized.controller';

@injectable()
Expand Down Expand Up @@ -37,6 +42,7 @@ export class OrganizationsController extends AuthorizedController {
async context => pipe(
context.req.valid('json'),
organizationsService.asUser(context.var.jwt).create,
rejectUnsafeCreateSdkErrors,
rejectUnsafeSdkErrors,
serializeSdkResponseTE<ReturnType<OrganizationsSdk['create']>>(context),
),
Expand Down
1 change: 1 addition & 0 deletions apps/backend/src/modules/api/helpers/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './reject-unsafe-create-sdk-errors';
export * from './reject-unsafe-sdk-errors';
export * from './respond-with-tagged-error';
export * from './sdk-hono-schema-validator';
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { taskEither as TE } from 'fp-ts';
import { pipe } from 'fp-ts/function';

import type { TaggedError } from '@llm/commons';

import {
isSdkTaggedError,
SdkRecordAlreadyExistsError,
} from '@llm/sdk';
import { LoggerService } from '~/modules/logger';

export function rejectUnsafeCreateSdkErrors<T, E extends TaggedError<string, any>>(task: TE.TaskEither<E, T>) {
const logger = LoggerService.of('rejectUnsafeSdkErrors');

return pipe(
task,
TE.mapLeft((error) => {
if (isSdkTaggedError(error)) {
return error;
}

const mappedError = (() => {
switch (error.tag) {
case 'DatabaseRecordAlreadyExists':
return new SdkRecordAlreadyExistsError({});

default:
return error;
}
})();

if (mappedError !== error) {
const { stack, ...context } = error;

logger.error(`Mapped creator SDK error - ${error.tag}!`, context);

if (stack) {
console.error(stack);
}
}

return mappedError;
}),
);
}
13 changes: 3 additions & 10 deletions apps/backend/src/modules/api/helpers/reject-unsafe-sdk-errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import type { TaggedError } from '@llm/commons';

import {
isSdkTaggedError,
SdkRecordAlreadyExistsError,
SdkServerError,
} from '@llm/sdk';
import { LoggerService } from '~/modules/logger';
Expand All @@ -28,15 +27,9 @@ export function rejectUnsafeSdkErrors<T, E extends TaggedError<string, any>>(tas
console.error(stack);
}

switch (error.tag) {
case 'DatabaseRecordAlreadyExists':
return new SdkRecordAlreadyExistsError({});

default:
return new SdkServerError({
message: 'Internal server error!',
});
}
return new SdkServerError({
message: 'Internal server error!',
});
}),
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export function createArchivedRecordMappings() {
return {
archived: { type: 'boolean' },
};
}
1 change: 1 addition & 0 deletions apps/backend/src/modules/elasticsearch/mappings/index.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
export * from './archived.mapping';
export * from './autocomplete.mapping';
export * from './dated-record.mapping';
export * from './id-name-object.mapping';
Expand Down
23 changes: 17 additions & 6 deletions apps/backend/src/modules/elasticsearch/repo/elasticsearch.repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,14 +156,21 @@ export class ElasticsearchRepo {
indexDocument = <D extends EsBaseDocument = EsBaseDocument>(
indexName: string,
{ _id, ...doc }: D,
{ waitForRecordAvailability }: EsIndexWaitAttributes = {},
{ waitForRecordAvailability = true }: EsIndexWaitAttributes = {},
) =>
pipe(
TaggedError.tryUnsafeTask(EsIndexingError, async () => this.client.index({
id: _id.toString(),
index: indexName,
body: doc,
})),
TaggedError.tryUnsafeTask(EsIndexingError, async () => {
this.logger.info('Trying to index document...', { _id, doc, indexName });

const result = await this.client.index({
id: _id.toString(),
index: indexName,
body: doc,
});

this.logger.info('Document indexed!', { _id, indexName });
return result;
}),

TE.chainW(() => (
waitForRecordAvailability
Expand Down Expand Up @@ -212,6 +219,8 @@ export class ElasticsearchRepo {
TE.tryCatch(
() => waitFor(
async () => {
this.logger.info('Waiting for document availability...', { indexName, id });

const result = await this.client.exists({
index: indexName,
id,
Expand All @@ -226,6 +235,8 @@ export class ElasticsearchRepo {
);
}

this.logger.info('Looks like document is available!', { indexName, id });

return true;
},
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { inject, injectable } from 'tsyringe';

import { tryOrThrowTE } from '@llm/commons';
import {
createArchivedRecordMappings,
createAutocompleteFieldAnalyzeSettings,
createBaseAutocompleteFieldMappings,
createBaseDatedRecordMappings,
Expand All @@ -25,6 +26,7 @@ const OrganizationsAbstractEsIndexRepo = createElasticsearchIndexRepo({
properties: {
...createBaseDatedRecordMappings(),
...createBaseAutocompleteFieldMappings(),
...createArchivedRecordMappings(),
max_number_of_users: { type: 'integer' },
},
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { inject, injectable } from 'tsyringe';

import { tryOrThrowTE } from '@llm/commons';
import {
createArchivedRecordMappings,
createAutocompleteFieldAnalyzeSettings,
createBaseAutocompleteFieldMappings,
createBaseDatedRecordMappings,
Expand All @@ -25,11 +26,11 @@ const UsersAbstractEsIndexRepo = createElasticsearchIndexRepo({
dynamic: false,
properties: {
...createBaseDatedRecordMappings(),
...createArchivedRecordMappings(),
...createBaseAutocompleteFieldMappings('email'),
role: { type: 'keyword' },
email: { type: 'text' },
active: { type: 'boolean' },
archived: { type: 'boolean' },
archive_protection: { type: 'boolean' },
auth: {
properties: {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
import { AbstractNestedSdkWithAuth } from '~/modules/abstract-nested-sdk-with-auth';
import { getPayload, performApiRequest, postPayload } from '~/shared';
import {
getPayload,
performApiRequest,
postPayload,
type SdkRecordAlreadyExistsError,
} from '~/shared';

import type {
SdkCreateOrganizationInputT,
Expand All @@ -19,7 +24,7 @@ export class OrganizationsSdk extends AbstractNestedSdkWithAuth {
});

create = (data: SdkCreateOrganizationInputT) =>
performApiRequest<SdkCreateOrganizationOutputT>({
performApiRequest<SdkCreateOrganizationOutputT, SdkRecordAlreadyExistsError>({
url: this.endpoint('/create'),
options: postPayload(data),
});
Expand Down
2 changes: 1 addition & 1 deletion packages/sdk/src/shared/dto/sdk-search-filters.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { z } from 'zod';
import { SdkTableRowIdV } from './sdk-table-row-id.dto';

export const SdkArchivedFiltersInputV = z.object({
archived: z.coerce.boolean().optional(),
archived: z.coerce.boolean().optional().default(false),
});

export const SdkIdsFiltersInputV = z.object({
Expand Down

0 comments on commit f5d689f

Please sign in to comment.