@sapphire/plugin-api
Version:
Plugin for @sapphire/framework to expose a REST API
141 lines (139 loc) • 3.09 kB
JavaScript
import { __name, __publicField } from '../../../chunk-S573YWRP.mjs';
import { ServerResponse, STATUS_CODES } from 'http';
import { Readable } from 'stream';
import 'stream/web';
import { HttpCodes } from '../http/HttpCodes.mjs';
var _ApiResponse = class _ApiResponse extends ServerResponse {
constructor() {
super(...arguments);
/**
* @since 1.0.0
*/
__publicField(this, "cookies");
}
/**
* @since 1.0.0
*/
ok(data = STATUS_CODES[HttpCodes.OK]) {
this.status(HttpCodes.OK);
return this.respond(data);
}
/**
* @since 1.0.0
*/
created(data = STATUS_CODES[HttpCodes.Created]) {
this.status(HttpCodes.Created);
return this.respond(data);
}
/**
* @since 1.0.0
*/
noContent(data = STATUS_CODES[HttpCodes.NoContent]) {
this.status(HttpCodes.NoContent);
return this.respond(data);
}
/**
* @since 1.0.0
*/
badRequest(data) {
return this.error(HttpCodes.BadRequest, data);
}
/**
* @since 1.0.0
*/
unauthorized(data) {
return this.error(HttpCodes.Unauthorized, data);
}
/**
* @since 1.0.0
*/
forbidden(data) {
return this.error(HttpCodes.Forbidden, data);
}
/**
* @since 1.0.0
*/
notFound(data) {
return this.error(HttpCodes.NotFound, data);
}
/**
* @since 7.0.0
*/
methodNotAllowed(data) {
return this.error(HttpCodes.MethodNotAllowed, data);
}
/**
* @since 1.0.0
*/
conflict(data) {
return this.error(HttpCodes.Conflict, data);
}
/**
* @since 1.0.0
*/
error(error, data) {
if (typeof error === "string") {
return this.status(HttpCodes.InternalServerError).json({ error });
}
return this.status(error).json({ error: data ?? STATUS_CODES[error] });
}
/**
* @since 1.0.0
*/
respond(data) {
return typeof data === "string" ? this.text(data) : this.json(data);
}
/**
* @since 1.0.0
*/
status(code) {
this.statusCode = code;
return this;
}
/**
* @since 1.0.0
*/
json(data) {
this.setContentType("application/json").end(JSON.stringify(data));
}
/**
* @since 1.0.0
*/
text(data) {
this.setContentType("text/plain").end(data);
}
/**
* @since 6.1.0
*
* Sets the image content type and sends the image data in the response.
*
* @param type - The MIME type of the image (e.g., 'image/png').
* @param data - The image data as a `string`, {@link Buffer}, {@link Uint8Array}, or {@link ReadableStream}.
*/
image(type, data) {
if (data instanceof Readable) {
this.setContentType(type);
data.pipe(this);
} else {
this.setContentType(type).end(data);
}
}
/**
* @since 5.1.0
*/
html(code, data) {
this.setContentType("text/html").status(code).end(data);
}
/**
* @since 1.0.0
*/
setContentType(contentType) {
this.setHeader("Content-Type", contentType);
return this;
}
};
__name(_ApiResponse, "ApiResponse");
var ApiResponse = _ApiResponse;
export { ApiResponse };
//# sourceMappingURL=ApiResponse.mjs.map
//# sourceMappingURL=ApiResponse.mjs.map