Skip to content

Commit

Permalink
fix(server): read body as string
Browse files Browse the repository at this point in the history
  • Loading branch information
pi0 committed Sep 28, 2023
1 parent 2644320 commit dfda25f
Showing 1 changed file with 13 additions and 12 deletions.
25 changes: 13 additions & 12 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,21 +41,20 @@ export function createH3StorageHandler(
opts: StorageServerOptions = {}
): EventHandler {
return eventHandler(async (event) => {
const method = getMethod(event);
const _path = opts.resolvePath?.(event) ?? event.path;
const isBaseKey = _path.endsWith(":") || _path.endsWith("/");
const key = isBaseKey ? normalizeBaseKey(_path) : normalizeKey(_path);

// Authorize Request
if (!(method in MethodToTypeMap)) {
if (!(event.method in MethodToTypeMap)) {
throw createError({
statusCode: 405,
statusMessage: `Method Not Allowed: ${method}`,
statusMessage: `Method Not Allowed: ${event.method}`,
});
}
try {
await opts.authorize?.({
type: MethodToTypeMap[method as keyof typeof MethodToTypeMap],
type: MethodToTypeMap[event.method as keyof typeof MethodToTypeMap],
event,
key,
});
Expand All @@ -71,7 +70,7 @@ export function createH3StorageHandler(
}

// GET => getItem
if (method === "GET") {
if (event.method === "GET") {
if (isBaseKey) {
const keys = await storage.getKeys(key);
return keys.map((key) => key.replace(/:/g, "/"));
Expand All @@ -89,7 +88,7 @@ export function createH3StorageHandler(
}

// HEAD => hasItem + meta (mtime)
if (method === "HEAD") {
if (event.method === "HEAD") {
const _hasItem = await storage.hasItem(key);
event.node.res.statusCode = _hasItem ? 200 : 404;
if (_hasItem) {
Expand All @@ -106,28 +105,30 @@ export function createH3StorageHandler(
}

// PUT => setItem
if (method === "PUT") {
if (event.method === "PUT") {
const isRaw =
getRequestHeader(event, "content-type") === "application/octet-stream";
if (isRaw) {
const value = await readRawBody(event);
await storage.setItemRaw(key, value);
} else {
const value = await readBody(event);
await storage.setItem(key, value);
const value = await readRawBody(event, "utf8");
if (value !== undefined) {
await storage.setItem(key, value);
}
}
return "OK";
}

// DELETE => removeItem
if (method === "DELETE") {
if (event.method === "DELETE") {
await (isBaseKey ? storage.clear(key) : storage.removeItem(key));
return "OK";
}

throw createError({
statusCode: 405,
statusMessage: `Method Not Allowed: ${method}`,
statusMessage: `Method Not Allowed: ${event.method}`,
});
});
}
Expand All @@ -136,7 +137,7 @@ export function createStorageServer(
storage: Storage,
options: StorageServerOptions = {}
): { handle: RequestListener } {
const app = createApp();
const app = createApp({ debug: true });
const handler = createH3StorageHandler(storage, options);
app.use(handler);
return {
Expand Down

0 comments on commit dfda25f

Please sign in to comment.