When processing is successful
import { Result } from 'types-ddd';
return Result.ok<T, F>(/* ... resource type T */);
T: first generic type refer to the value to return in success case.
F: second one refer to the error type to return in failure case. By default is string
The resource accepts a generic type. It can be a primary type or a more dynamic type.
return Result.ok<string>("Hello World");
It do not throw error and return an object with attributes and result status
const result = Result.ok<string>("simple string");
console.log(result)
> Result {
isSuccess: true,
isFailure: false,
error: null,
_value: "simple string",
statusCodeNumber: 200,
statusCode: "OK"
}
The returned value must be accessed by your key to get a result
const result = Result.ok<string>("simple string");
console.log(result.getResult())
> "simple string"
How to confirm that the return is really successful
const result = Result.ok<string>("simple string");
console.log(result.isSuccess);
> true
How to return an interface
class User {
name: string;
}
const result = Result.ok<User>({name: "John"});
console.log(result.getResult())
> Object { name: "John" }
If you declared the return as an interface and returned a value other than the one defined. You will have an error
class User {
name: string;
}
const result = Result.ok<User>("this is not user"); // Error
Result also accpet statusCode optionally, if you want to provide domain status for infra.
Result.ok<string>("Some success message", "OK");
// Available status success
CONTINUE = 100,
SWITCHING_PROTOCOL = 101,
PROCESSING = 102,
OK = 200,
CREATED = 201,
ACCEPTED = 202,
NON_AUTHORITATIVE = 203,
NO_CONTENT = 204,
RESET_CONTENT = 205,
PARTIAL_CONTENT = 206,
By default
success result has status "OK" = 200
failure result has "UNPROCESSABLE_ENTITY" = 422
You also can return a void using Result.success instead Result.ok. Let's see a real use case
const saveUser = async (user:User):Promise<Result<void>> => {
try{
await connection.save(user);
// for void use Result.success
return Result.success<void>();
}
catch(error){
return Result.fail<void>(error.message, "INTERNAL_SERVER_ERROR");
}
}
// get result
const result => await saveUser(user);
console.log(result.isSuccess);
> true
It is possible to define an internationalization error message
interface IUser {
name: string;
}
interface IErrorMessage {
PT_BR: string;
EN_US: string;
}
const createUser = (name: string): Result<IUser, IErrorMessage> => {
if (name.length > 20 && name.length < 3) {
return Result.fail({ PT_BR: "Nome inválido", EN_US: "Invalid name" })
}
else {
return Result.ok({ name });
}
}
const userOrError = createUser("Valid name");
console.log(userOrError.isSuccess);
> true
const newUserOrError = createUser("");
console.log(newUserOrError.error.EN_US);
> "Invalid name"