MCPcopy
hub / github.com/browserless/browserless / writeResponse

Function writeResponse

src/utils.ts:171–216  ·  view source on GitHub ↗
(
  writeable: Duplex | ServerResponse,
  httpCode: keyof typeof codes,
  message: string | Error,
  contentType: contentTypes = contentTypes.text,
)

Source from the content-addressed store, hash-verified

169 isHTTP(connection) ? !!connection.socket?.writable : !!connection.writable;
170
171export const writeResponse = (
172 writeable: Duplex | ServerResponse,
173 httpCode: keyof typeof codes,
174 message: string | Error,
175 contentType: contentTypes = contentTypes.text,
176): void => {
177 if (!isConnected(writeable)) {
178 return;
179 }
180
181 const isJSON = contentType.includes(contentTypes.json);
182 const isError = httpCode >= 400;
183 const httpMessage = codes[httpCode];
184 const CTTHeader = contentType.toLowerCase().includes('charset=')
185 ? contentType
186 : `${contentType}; charset=${encodings.utf8}`;
187 const body =
188 isJSON && isError
189 ? JSON.stringify({
190 error: message instanceof Error ? message.message : message,
191 })
192 : message;
193
194 if (isHTTP(writeable)) {
195 const response = writeable;
196 if (!response.headersSent) {
197 response.writeHead(httpMessage.code, { 'Content-Type': CTTHeader });
198 response.end(body + '\n');
199 }
200 return;
201 }
202
203 const httpResponse = [
204 httpMessage.message,
205 `Content-Type: ${CTTHeader}`,
206 'Content-Encoding: UTF-8',
207 'Accept-Ranges: bytes',
208 'Connection: keep-alive',
209 '\r\n',
210 body,
211 ].join('\r\n');
212
213 writeable.write(httpResponse);
214 writeable.end();
215 return;
216};
217
218export const jsonResponse = (
219 response: ServerResponse,

Callers 15

onQueueFullHTTPMethod · 0.85
onQueueFullWebSocketMethod · 0.85
onHTTPTimeoutMethod · 0.85
onWebsocketTimeoutMethod · 0.85
wrapHTTPHandlerMethod · 0.85
wrapWebSocketHandlerMethod · 0.85
utils.spec.tsFile · 0.85
handleErrorRequestMethod · 0.85
onHTTPUnauthorizedMethod · 0.85
handleRequestUnsafeMethod · 0.85
handleWebSocketUnsafeMethod · 0.85

Calls 3

isConnectedFunction · 0.85
isHTTPFunction · 0.85
writeMethod · 0.80

Tested by

no test coverage detected