Skip to content

Instantly share code, notes, and snippets.

@waldemarnt
Last active July 17, 2022 23:59
Show Gist options
  • Save waldemarnt/9b554834f7ed2f4341967f58ac4b59cd to your computer and use it in GitHub Desktop.
Save waldemarnt/9b554834f7ed2f4341967f58ac4b59cd to your computer and use it in GitHub Desktop.
Thiago TS exemplo
export type Result<E, S> = Failure<E, S> | Success<E, S>;
export class Failure<E, S> {
constructor(private _value: E) {}
isError(): this is Failure<E, S> {
return true;
}
value(): E {
return this._value;
}
isSuccess(): this is Success<E, S> {
return false;
}
}
export class Success<E, S> {
constructor(private _value: S) {}
value(): S {
return this._value;
}
isError(): this is Failure<E, S> {
return true;
}
isSuccess(): this is Success<E, S> {
return true;
}
}
type CreateUserResult = Result<UserAlreadyExistsError | UnexpectedError, User>;
export class CreateUserUseCase {
execute(params: any): CreateUserResult {
return {} as CreateUserResult;
}
}
class UserAlreadyExistsError extends Error {}
class UnexpectedError extends Error {}
//uma entitade base é necessário para ser usada na classe abstrata
class Entity {
constructor(private name: string) {}
}
class User extends Entity {
constructor(name: string) {
super(name);
}
}
class CreateUserController {
create(request: any): any {
const createUserResult = new CreateUserUseCase().execute({});
const createUserHttpResponseFactory = new CreateUserHttpResponseFactory();
return createUserHttpResponseFactory.make(createUserResult);
}
}
abstract class HttpResponseFactory<T extends Result<Error, Entity>> {
public make(result: T) {
if (result.isError()) return this.parseError(result.value());
return this.parseSucess(result.value());
}
//Recebe o error aqui
protected parseError<E extends Error>(result: E) {
//return response.status(HttpCode.InternalServerError).json({});
}
//Se for sucesso ele recebe algo que extends Entity, por exemplo User
protected abstract parseSucess<S extends Entity>(result: S): any;
}
class CreateUserHttpResponseFactory extends HttpResponseFactory<CreateUserResult> {
protected parseError(result: UserAlreadyExistsError | UnexpectedError): any {}
protected parseSucess(result: User): any {}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment