Skip to content

Commit 24bc60f

Browse files
committed
fix: require files for uploads
1 parent 62ba8e6 commit 24bc60f

2 files changed

Lines changed: 66 additions & 3 deletions

File tree

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,12 @@
1-
import { ok } from "../utils/response.js";
1+
import { fail, ok } from "../utils/response.js";
22

33
export async function uploadFile(req, res) {
4+
if (!req.file) {
5+
return fail(res, "File is required", 400);
6+
}
7+
48
return ok(res, {
5-
filename: req.file?.originalname ?? null,
6-
status: req.file ? "uploaded" : "no-file"
9+
filename: req.file.originalname,
10+
status: "uploaded"
711
}, 201);
812
}

apps/api/src/tests/upload.test.js

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import test from "node:test";
2+
import assert from "node:assert/strict";
3+
import { createApp } from "../app.js";
4+
5+
async function withServer(run) {
6+
const app = createApp();
7+
const server = app.listen(0);
8+
9+
await new Promise((resolve, reject) => {
10+
server.once("listening", resolve);
11+
server.once("error", reject);
12+
});
13+
14+
try {
15+
const { port } = server.address();
16+
await run(`http://127.0.0.1:${port}`);
17+
} finally {
18+
await new Promise((resolve, reject) => {
19+
server.close((error) => (error ? reject(error) : resolve()));
20+
});
21+
}
22+
}
23+
24+
test("POST /api/uploads rejects requests without a file", async () => {
25+
await withServer(async (baseUrl) => {
26+
const response = await fetch(`${baseUrl}/api/uploads`, {
27+
method: "POST",
28+
});
29+
const payload = await response.json();
30+
31+
assert.equal(response.status, 400);
32+
assert.deepEqual(payload, {
33+
success: false,
34+
message: "File is required",
35+
});
36+
});
37+
});
38+
39+
test("POST /api/uploads still accepts a file upload", async () => {
40+
await withServer(async (baseUrl) => {
41+
const form = new FormData();
42+
form.append("file", new Blob(["hello"], { type: "text/plain" }), "hello.txt");
43+
44+
const response = await fetch(`${baseUrl}/api/uploads`, {
45+
method: "POST",
46+
body: form,
47+
});
48+
const payload = await response.json();
49+
50+
assert.equal(response.status, 201);
51+
assert.deepEqual(payload, {
52+
success: true,
53+
data: {
54+
filename: "hello.txt",
55+
status: "uploaded",
56+
},
57+
});
58+
});
59+
});

0 commit comments

Comments
 (0)