-
Notifications
You must be signed in to change notification settings - Fork 5
/
http.ts
196 lines (180 loc) · 5.14 KB
/
http.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
import { config, log } from "../ports";
import {
AggregateFactory,
CommandHandlerFactory,
Errors,
Messages,
ProjectionQuery,
ProjectionRecord,
ProjectorFactory,
Snapshot,
State
} from "../types";
import { decamelize } from "./formatting";
import { patch } from "./patch";
import { toProjectionQueryString } from "./query";
export type HttpStatusCode = 200 | 400 | 401 | 403 | 404 | 409 | 500;
export type HttpResponse<T> = {
status: HttpStatusCode;
statusText?: string;
result?: T;
error?: {
message: string;
details?: any;
stack?: string;
};
};
export const Ok = <T>(result?: any): HttpResponse<T> => ({
status: 200,
statusText: "OK",
result
});
export const BadRequest = (
message?: string,
details?: any
): HttpResponse<never> => ({
status: 400,
statusText: "Bad Request",
error: { message: message ?? "Bad Request", details }
});
export const Unauthorized = (message?: string): HttpResponse<never> => ({
status: 401,
statusText: "Unauthorized",
error: { message: message ?? "Unauthorized" }
});
export const Forbidden = (message?: string): HttpResponse<never> => ({
status: 403,
statusText: "Forbidden",
error: { message: message ?? "Forbidden" }
});
export const NotFound = (message?: string): HttpResponse<never> => ({
status: 404,
statusText: "Not Found",
error: { message: message ?? "Not Found" }
});
export const Conflict = (message?: string): HttpResponse<never> => ({
status: 409,
statusText: "Conflict",
error: { message: message ?? "Conflict" }
});
export const InternalServerError = (
message?: string,
stack?: string
): HttpResponse<never> => ({
status: 500,
statusText: "Internal Server Error",
error: {
message: message ?? "Internal Server Error",
stack: config().env !== "production" ? stack : undefined
}
});
/**
* Converts error to HttpResponse with error
*/
export const httpError = (error: unknown): HttpResponse<never> => {
if (error instanceof Error) {
const { name, message, stack } = error;
switch (name) {
case Errors.ValidationError:
case Errors.InvariantError:
return BadRequest(message, "details" in error && error.details);
case Errors.RegistrationError:
return NotFound(message);
case Errors.ConcurrencyError:
case Errors.ActorConcurrencyError:
return Conflict(message);
}
return InternalServerError(message, stack);
}
return InternalServerError(
typeof error === "string" ? error : "Oops, something went wrong!"
);
};
export type Proxy = {
command: <
S extends State,
C extends Messages,
E extends Messages,
N extends keyof C & string
>(
factory: CommandHandlerFactory<S, C, E>,
stream: string,
name: N,
data: C[N],
expectedVersion?: number
) => Promise<HttpResponse<Snapshot<S>>>;
load: <S extends State, C extends Messages, E extends Messages>(
factory: AggregateFactory<S, C, E>,
stream: string
) => Promise<HttpResponse<Snapshot<S>> | undefined>;
query: <S extends State, E extends Messages>(
factory: ProjectorFactory<S, E>,
query: ProjectionQuery<S>
) => Promise<HttpResponse<ProjectionRecord<S>[]>>;
};
/**
* Http api proxy
*
* @param apiUrl api host url
* @param options fetch options
* @param responseMapper optional reponse body mapper
*/
export const HttpProxy = (
apiUrl: string,
options?: RequestInit,
responseMapper?: <T>(response: any) => HttpResponse<T>
): Proxy => {
return {
command: async function (factory, stream, name, data, expectedVersion) {
const url = `${apiUrl}/${decamelize(factory.name)}/${stream}/${decamelize(
name
)}`;
log().blue().trace("> Command", url, data);
const opts = patch(options ?? {}, {
method: "POST",
body: JSON.stringify(data),
headers: {
"Content-Type": "application/json",
"If-Match": expectedVersion ? expectedVersion.toString() : ""
}
}) as RequestInit;
try {
const response = await fetch(url, opts);
const body = await response.json();
log().trace("< ", body);
return responseMapper ? responseMapper(body) : Ok(body);
} catch (error) {
return httpError(error);
}
},
load: async function (factory, stream) {
const url = `${apiUrl}/${decamelize(factory.name)}/${stream}`;
try {
const response = await fetch(url, {
...options,
method: "GET"
});
const body = await response.json();
return responseMapper ? responseMapper(body) : Ok(body);
} catch (error) {
return httpError(error);
}
},
query: async function (factory, query) {
const url = `${apiUrl}/${decamelize(factory.name)}`;
const qs = toProjectionQueryString(query as ProjectionQuery);
log().gray().trace("> Query", url, qs);
try {
const response = await fetch(`${url}?${qs}`, {
...options,
method: "GET"
});
const body = await response.json();
log().trace("< ", body);
return responseMapper ? responseMapper(body) : Ok(body);
} catch (error) {
return httpError(error);
}
}
};
};