Compare commits

...

9 Commits

Author SHA1 Message Date
Sugui e263f1eaca yarn.lock
Unit Tests with docker compose / unit-test (pull_request) Successful in 1m28s Details
2024-01-06 20:49:42 +01:00
Sugui 18b47cc20e Merge remote-tracking branch 'origin/develop' into get-images 2024-01-06 20:49:24 +01:00
Alie cf03c90c46 changed the action to use cache (#19)
Reviewed-on: #19
Co-authored-by: Alie <bizcochito@anartist.org>
Co-committed-by: Alie <bizcochito@anartist.org>
2024-01-06 18:57:40 +00:00
bizcochito 478487d402 Merge pull request 'put-images' (#18) from put-images into develop
Reviewed-on: #18
2024-01-06 12:45:36 +00:00
Suguivy e2c02cb32c Merge pull request 'Added fake data for test and dev environment' (#17) from testing into develop
Reviewed-on: #17
2024-01-06 12:34:44 +00:00
bizcochito eefb55a092 Merge branch 'develop' into put-images
Unit Tests with docker compose / unit-test (pull_request) Successful in 3m27s Details
2024-01-06 12:34:16 +00:00
Alie fb2d947913 added a functional test and optimized a test
Unit Tests with docker compose / unit-test (pull_request) Successful in 6m7s Details
2024-01-06 13:10:45 +01:00
Alie ebf2ec17d1 added tests and auth to PUT images 2024-01-06 12:57:22 +01:00
Alie f74a0f26cc made the endpoint, works with manual tests 2024-01-06 12:24:30 +01:00
9 changed files with 162 additions and 14 deletions

View File

@ -6,15 +6,17 @@ jobs:
container: container:
image: docker:dind image: docker:dind
volumes: volumes:
- /var/lib/docker:/var/lib/docker - /usr/local/share/.cache/yarn:/usr/local/share/.cache/yarn
- /var/lib/docker/image:/var/lib/docker/image
- /var/lib/docker/overlay2:/var/lib/docker/overlay2
steps: steps:
- name: Starting docker daemon - name: Starting docker daemon
run: docker-init -- dockerd --host=unix:///var/run/docker.sock & run: docker-init -- dockerd --host=unix:///var/run/docker.sock &
- name: Installing necessary packages - name: Installing necessary packages
run: apk add npm git curl bash run: apk add yarn git curl bash
- name: Check out repository code - name: Check out repository code
uses: actions/checkout@v3 uses: actions/checkout@v3
- name: Install project dependencies - name: Install project dependencies
run: npm install run: yarn install --frozen-lockfile --ignore-scripts
- name: Run docker-compose - name: Run docker-compose
run: docker compose down -v && docker compose run bot-api bun test run: docker compose down -v && docker compose run bot-api bun test

View File

@ -37,13 +37,12 @@ bun install
To run: To run:
```bash ```bash
docker compose up bun run dev
``` ```
For testing, remember: For testing, remember:
```bash ```bash
docker compose down -v bun run test
docker compose run bot-api bun run test
``` ```
This project was created using `bun init` in bun v1.0.13. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime. This project was created using `bun init` in bun v1.0.13. [Bun](https://bun.sh) is a fast all-in-one JavaScript runtime.

4
bunfig.toml Normal file
View File

@ -0,0 +1,4 @@
[install.lockfile]
# whether to save a non-Bun lockfile alongside bun.lockb
# only "yarn" is supported
print = "yarn"

View File

@ -1,5 +1,5 @@
{ {
"name": "fib-api", "name": "bot-api",
"module": "index.ts", "module": "index.ts",
"type": "module", "type": "module",
"devDependencies": { "devDependencies": {

View File

@ -15,6 +15,7 @@ app.get("/", (_, res) => {
app.get("/images", imageController.getAllImages); app.get("/images", imageController.getAllImages);
app.get("/images/:id", imageController.getImageById); app.get("/images/:id", imageController.getImageById);
app.put("/images/:id", authControler.authorize, imageController.editImage);
app.post("/images", authControler.authorize, imageController.addImage); app.post("/images", authControler.authorize, imageController.addImage);
app.post("/login", authControler.login); app.post("/login", authControler.login);
@ -30,6 +31,7 @@ export const startApp = async () => {
user: mongo_user, user: mongo_user,
pass: mongo_pass, pass: mongo_pass,
}); });
mongoose.set("runValidators", true);
app.listen(port, () => app.listen(port, () =>
console.log(`Express server listening on port ${port}`) console.log(`Express server listening on port ${port}`)
); );

View File

@ -4,6 +4,34 @@ import mongoose, { mongo } from "mongoose";
import { Image } from "../models/ImageModel"; import { Image } from "../models/ImageModel";
class ImageController { class ImageController {
async editImage(req: Request, res: Response) {
try {
const change: Image = req.body;
const result = await imageService.replaceOne(req.params.id, change);
if (result.matchedCount > 0) {
res.status(204).json();
} else {
res.status(404).json({ error: "Image not found" });
}
} catch (error: any) {
if (error instanceof mongoose.Error.CastError) {
res.status(400).json({ error: "Invalid Id" });
} else if (error instanceof mongoose.Error.ValidationError) {
// Should return 400 Bad request for invalid requests
res.status(400).json({ error: error.message });
} else if (
error instanceof mongo.MongoServerError &&
error.code === 11000
) {
// Should return 409 Conflict for existing urls
res.status(409).json({
error: `the image with URL ${error.keyValue.url} already exists`,
});
} else {
res.status(500).json({ error: "Internal Server Error" });
}
}
}
async getImageById(req: Request, res: Response) { async getImageById(req: Request, res: Response) {
try { try {
const image = await imageService.findById(req.params.id); const image = await imageService.findById(req.params.id);

View File

@ -1,6 +1,10 @@
import imageModel, { Image } from "../models/ImageModel"; import imageModel, { Image } from "../models/ImageModel";
class ImageService { class ImageService {
async replaceOne(id: string, newimage: Image) {
const result = await imageModel.updateOne({ _id: id }, newimage);
return result;
}
async findById(id: string) { async findById(id: string) {
const image = await imageModel.findOne({ _id: id }); const image = await imageModel.findOne({ _id: id });
return image; return image;

View File

@ -229,7 +229,6 @@ describe("POST /images works properly", () => {
}); });
it("should return 400 for malformed requests", async () => { it("should return 400 for malformed requests", async () => {
mock.restore();
const res = await request(app) const res = await request(app)
.post("/images") .post("/images")
.set("authorization", `Bearer ${token}`) .set("authorization", `Bearer ${token}`)
@ -242,18 +241,23 @@ describe("POST /images works properly", () => {
}); });
}); });
describe("GET /images/:id works properly", () => { describe("GET /images/<id> works properly", () => {
let id: string;
let list: Image[];
beforeAll(async () => {
const res = await request(app).get("/images");
list = res.body.images;
id = list[0]._id;
});
it("should return 200 for existing ids", async () => { it("should return 200 for existing ids", async () => {
const list = await request(app).get("/images");
const id = list.body.images[0]._id;
const res = await request(app).get(`/images/${id}`); const res = await request(app).get(`/images/${id}`);
expect(res.status).toBe(200); expect(res.status).toBe(200);
}); });
it("should return 404 for non-existing ids", async () => { it("should return 404 for non-existing ids", async () => {
const list = await request(app).get("/images");
const id = "000000000000000000000000"; // this was the least posible to exist ID const id = "000000000000000000000000"; // this was the least posible to exist ID
if (!(id in list.body.images)) { if (!(id in list)) {
const res = await request(app).get(`/images/${id}`); const res = await request(app).get(`/images/${id}`);
expect(res.status).toBe(404); expect(res.status).toBe(404);
} }
@ -264,3 +268,108 @@ describe("GET /images/:id works properly", () => {
expect(res.status).toBe(400); expect(res.status).toBe(400);
}); });
}); });
describe("PUT /images/<id> works properly", () => {
let id: string;
let list: Image[];
beforeAll(async () => {
const res = await request(app).get("/images");
list = res.body.images;
id = list[0]._id;
});
it("should return 204 for valid modifications", async () => {
const res = await request(app)
.put(`/images/${id}`)
.set("authorization", `Bearer ${token}`)
.send({ status: "available" });
expect(res.status).toBe(204);
});
it("should return 404 for non-existing ids", async () => {
const id = "000000000000000000000000"; // this was the least posible to exist ID
if (!(id in list)) {
const res = await request(app)
.put(`/images/${id}`)
.set("authorization", `Bearer ${token}`)
.send({ status: "available" });
expect(res.status).toBe(404);
}
});
it("should return 400 for malformed ids", async () => {
const res = await request(app)
.put("/images/98439384")
.set("authorization", `Bearer ${token}`)
.send({ status: "available" });
expect(res.status).toBe(400);
expect(res.body).toEqual({ error: "Invalid Id" });
});
it("should return 400 for malformed requests", async () => {
const res = await request(app)
.put(`/images/${id}`)
.set("authorization", `Bearer ${token}`)
.send({ status: "wrong" });
expect(res.status).toBe(400);
});
it("should return 409 if we try to modify the url into an existing one", async () => {
const res = await request(app)
.put(`/images/${id}`)
.set("authorization", `Bearer ${token}`)
.send({ url: "https://test.url.com/2" });
expect(res.status).toBe(409);
});
it("should return 500 for an error on the service", async () => {
mock.module("../src/services/ImageService", () => ({
default: {
replaceOne: () => {
throw new Error("This is an expected testing error");
},
},
}));
const res = await request(app)
.put(`/images/${id}`)
.set("authorization", `Bearer ${token}`)
.send({ status: "available" });
expect(res.status).toBe(500);
});
it("should return 401 for unauthenticated requests", async () => {
const res = await request(app)
.put(`/images/${id}`)
.send({ status: "available" });
expect(res.status).toBe(401);
});
it("should return 403 for invalid tokens", async () => {
const res = await request(app)
.put(`/images/${id}`)
.set("authorization", `Bearer token`)
.send({ status: "available" });
expect(res.status).toBe(403);
});
it("should have its changes be reflected onto the DB", async () => {
const image = await request(app)
.post("/images")
.set("authorization", `Bearer ${token}`)
.send({
url: "https://test.url.com/5",
status: "available",
tags: ["2girls", "touhou"],
});
const id = image.body.image._id;
await request(app)
.put(`/images/${id}`)
.set("authorization", `Bearer ${token}`)
.send({ status: "consumed" });
const res = await request(app).get(`/images/${id}`);
expect(res.body.image).toHaveProperty("status", "consumed");
})
});