• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright (C) 2023 The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//      http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15export enum ResultStatus {
16  PENDING = 'pending',
17  SUCCESS = 'success',
18  ERROR = 'error',
19}
20
21export interface PendingResult {
22  status: ResultStatus.PENDING;
23}
24
25export interface ErrorResult {
26  status: ResultStatus.ERROR;
27  error: string;
28}
29
30export interface SuccessResult<T> {
31  status: ResultStatus.SUCCESS;
32  data: T;
33}
34
35export type Result<T> = PendingResult | ErrorResult | SuccessResult<T>;
36
37export function isError<T>(result: Result<T>): result is ErrorResult {
38  return result.status === ResultStatus.ERROR;
39}
40
41export function isPending<T>(result: Result<T>): result is PendingResult {
42  return result.status === ResultStatus.PENDING;
43}
44
45export function isSuccess<T>(result: Result<T>): result is SuccessResult<T> {
46  return result.status === ResultStatus.SUCCESS;
47}
48
49export function pending(): PendingResult {
50  return {status: ResultStatus.PENDING};
51}
52
53export function error(message: string): ErrorResult {
54  return {
55    status: ResultStatus.ERROR,
56    error: message,
57  };
58}
59
60export function success<T>(data: T): SuccessResult<T> {
61  return {
62    status: ResultStatus.SUCCESS,
63    data,
64  };
65}
66