diff --git a/package-lock.json b/package-lock.json index c1a7c7b..8bf9d11 100644 --- a/package-lock.json +++ b/package-lock.json @@ -9,6 +9,7 @@ "version": "1.0.0", "license": "ISC", "dependencies": { + "axios": "1.7.2", "express": "^4.18.2" }, "devDependencies": { @@ -16,6 +17,7 @@ "@types/node": "^20.11.18", "eslint": "^8.56.0", "jest": "^29.7.0", + "nock": "13.5.4", "supertest": "^6.3.4" } }, @@ -1599,8 +1601,17 @@ "node_modules/asynckit": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", - "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", - "dev": true + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, + "node_modules/axios": { + "version": "1.7.2", + "resolved": "https://eurostar.jfrog.io/eurostar/api/npm/npm/axios/-/axios-1.7.2.tgz", + "integrity": "sha512-2A8QhOMrbomlDuiLeK9XibIBzuHeRcqqNOHp0Cyp5EoJ1IFDh+XZH3A6BkXtv0K4gFGCI0Y4BM7B1wOEi0Rmgw==", + "dependencies": { + "follow-redirects": "^1.15.6", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } }, "node_modules/babel-jest": { "version": "29.7.0", @@ -1969,7 +1980,6 @@ "version": "1.0.8", "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", - "dev": true, "dependencies": { "delayed-stream": "~1.0.0" }, @@ -2128,7 +2138,6 @@ "version": "1.0.0", "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", - "dev": true, "engines": { "node": ">=0.4.0" } @@ -2675,11 +2684,29 @@ "integrity": "sha512-36yxDn5H7OFZQla0/jFJmbIKTdZAQHngCedGxiMmpNfEZM0sdEeT+WczLQrjK6D7o2aiyLYDnkw0R3JK0Qv1RQ==", "dev": true }, + "node_modules/follow-redirects": { + "version": "1.15.6", + "resolved": "https://eurostar.jfrog.io/eurostar/api/npm/npm/follow-redirects/-/follow-redirects-1.15.6.tgz", + "integrity": "sha512-wWN62YITEaOpSK584EZXJafH1AGpO8RVgElfkuXbTOrPX4fIfOyEpW/CsiNd8JdYrAoOvafRTOEnvsO++qCqFA==", + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, "node_modules/form-data": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", - "dev": true, "dependencies": { "asynckit": "^0.4.0", "combined-stream": "^1.0.8", @@ -3911,6 +3938,12 @@ "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", "dev": true }, + "node_modules/json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://eurostar.jfrog.io/eurostar/api/npm/npm/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==", + "dev": true + }, "node_modules/json5": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", @@ -4166,6 +4199,43 @@ "node": ">= 0.6" } }, + "node_modules/nock": { + "version": "13.5.4", + "resolved": "https://eurostar.jfrog.io/eurostar/api/npm/npm/nock/-/nock-13.5.4.tgz", + "integrity": "sha512-yAyTfdeNJGGBFxWdzSKCBYxs5FxLbCg5X5Q4ets974hcQzG1+qCxvIyOo4j2Ry6MUlhWVMX4OoYDefAIIwupjw==", + "dev": true, + "dependencies": { + "debug": "^4.1.0", + "json-stringify-safe": "^5.0.1", + "propagate": "^2.0.0" + }, + "engines": { + "node": ">= 10.13" + } + }, + "node_modules/nock/node_modules/debug": { + "version": "4.3.5", + "resolved": "https://eurostar.jfrog.io/eurostar/api/npm/npm/debug/-/debug-4.3.5.tgz", + "integrity": "sha512-pt0bNEmneDIvdL1Xsd9oDQ/wrQRkXDT4AUWlNZNPKvW5x/jyO9VFXkJUP07vQ2upmw5PlaITaPKc31jK13V+jg==", + "dev": true, + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/nock/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://eurostar.jfrog.io/eurostar/api/npm/npm/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==", + "dev": true + }, "node_modules/node-int64": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/node-int64/-/node-int64-0.4.0.tgz", @@ -4513,6 +4583,15 @@ "node": ">= 6" } }, + "node_modules/propagate": { + "version": "2.0.1", + "resolved": "https://eurostar.jfrog.io/eurostar/api/npm/npm/propagate/-/propagate-2.0.1.tgz", + "integrity": "sha512-vGrhOavPSTz4QVNuBNdcNXePNdNMaO1xj9yBeH1ScQPjk/rhg9sSlCXPhMkFuaNNW/syTvYqsnbIJxMBfRbbag==", + "dev": true, + "engines": { + "node": ">= 8" + } + }, "node_modules/proxy-addr": { "version": "2.0.7", "resolved": "https://registry.npmjs.org/proxy-addr/-/proxy-addr-2.0.7.tgz", @@ -4525,6 +4604,11 @@ "node": ">= 0.10" } }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://eurostar.jfrog.io/eurostar/api/npm/npm/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, "node_modules/punycode": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", diff --git a/package.json b/package.json index 787c8ca..4bb5d7a 100644 --- a/package.json +++ b/package.json @@ -14,13 +14,15 @@ "author": "Build Circle Ltd", "license": "ISC", "dependencies": { + "axios": "1.7.2", "express": "^4.18.2" }, "devDependencies": { - "supertest": "^6.3.4", "@types/jest": "^29.5.12", "@types/node": "^20.11.18", "eslint": "^8.56.0", - "jest": "^29.7.0" + "jest": "^29.7.0", + "nock": "13.5.4", + "supertest": "^6.3.4" } } diff --git a/src/battle.js b/src/battle.js index 57c5dad..1c8d0f6 100644 --- a/src/battle.js +++ b/src/battle.js @@ -1,12 +1,35 @@ -const getCharacters = require('./getCharacters') +const getCharacters = require("./getCharacters"); -function battle(heroName, villainName) { - const characters = getCharacters() +async function battle(heroName, villainName) { + const characters = await getCharacters(); - const hero = characters.items.find(e => e.name === heroName) - const villain = characters.items.find(e => e.name === villainName) + const hero = characters.items.find(e => e.name === heroName); + const villain = characters.items.find(e => e.name === villainName); - return hero.score >= villain.score ? hero : villain + if (!hero || !villain) { + throw new Error("failed to find characters"); + } + + let heroScore = hero.score; + let villainScore = villain.score; + + if (hero.weakness === villain.name) { + // I decided to add score rather than subtract, + // as it will elliminate the need to check for negative scores + villainScore += 1; + } + + if (villain.weakness === hero.name) { + heroScore += 1; + } + + if (heroScore === villainScore) { + return null; + } + + return heroScore >= villainScore + ? { ...hero, score: heroScore } + : { ...villain, score: villainScore }; } -module.exports = battle \ No newline at end of file +module.exports = battle; diff --git a/src/battle.spec.js b/src/battle.spec.js index d54bf1e..e45f199 100644 --- a/src/battle.spec.js +++ b/src/battle.spec.js @@ -1,15 +1,174 @@ -const battle = require('./battle') -const getCharacters = require('./getCharacters') +const battle = require("./battle"); +const getCharacters = require("./getCharacters"); -jest.mock('./getCharacters') +jest.mock("./getCharacters"); -it('battle should return the hero if they have a higher score', () => { - getCharacters.mockReturnValue({ - items: [ - {name: 'Winner', score: 9.0, type: 'hero'}, - {name: 'Loser', score: 8.0, type: 'villain'} - ] - }) +describe("battle", () => { + it("battle should return the hero if they have a higher score", async () => { + // Arrange + getCharacters.mockResolvedValue({ + items: [ + { name: "Winner", score: 9.0, type: "hero" }, + { name: "Loser", score: 8.0, type: "villain" } + ] + }); - expect(battle('Winner', 'Loser')).toEqual({name: "Winner", score: 9.0, type: 'hero'}) -}) \ No newline at end of file + // Act + const result = await battle("Winner", "Loser"); + + // Assert + expect(result).toHaveProperty("name", "Winner"); + expect(result).toHaveProperty("type", "hero"); + }); + + it("battle should return the villain if they have a higher score", async () => { + // Arrange + getCharacters.mockResolvedValue({ + items: [ + { name: "Loser", score: 8.0, type: "hero" }, + { name: "Winner", score: 9.0, type: "villain" } + ] + }); + + // Act + const result = await battle("Loser", "Winner"); + + // Assert + expect(result).toHaveProperty("name", "Winner"); + expect(result).toHaveProperty("type", "villain"); + }); + + it("battle should return null if they have the same score", async () => { + // Arrange + getCharacters.mockResolvedValue({ + items: [ + { name: "Foo", score: 9.0, type: "hero" }, + { name: "Bar", score: 9.0, type: "villain" } + ] + }); + + // Act + const result = await battle("Foo", "Bar"); + + // Assert + expect(result).toBeNull(); + }); + + it("battle should return a winner if two heroes are fighting", async () => { + // Arrange + getCharacters.mockResolvedValue({ + items: [ + { name: "Superman", score: 8.0, type: "hero" }, + { name: "Batman", score: 9.0, type: "hero" } + ] + }); + + // Act + const result = await battle("Superman", "Batman"); + + // Assert + expect(result).toHaveProperty("name", "Batman"); + }); + + it("battle should return a winner if two villains are fighting", async () => { + // Arrange + getCharacters.mockResolvedValue({ + items: [ + { name: "Joker", score: 8.0, type: "villain" }, + { name: "Penguin", score: 9.0, type: "villain" } + ] + }); + + // Act + const result = await battle("Joker", "Penguin"); + + // Assert + expect(result).toHaveProperty("name", "Penguin"); + }); + + it("should throw an error if the hero does not exist", async () => { + // Arrange + getCharacters.mockResolvedValue({ + items: [ + { name: "Superman", score: 8.0, type: "hero" }, + { name: "Batman", score: 9.0, type: "hero" } + ] + }); + + // Act + const result = battle("Spiderman", "Batman"); + + // Assert + await expect(result).rejects.toThrow("failed to find characters"); + }); + + it("should compare score float values", async () => { + // Arrange + getCharacters.mockResolvedValue({ + items: [ + { name: "Superman", score: 8.0, type: "hero" }, + { name: "Batman", score: 8.1, type: "hero" } + ] + }); + + // Act + const result = await battle("Superman", "Batman"); + + // Assert + expect(result).toHaveProperty("name", "Batman"); + }); + + // I decided to add score rather than subtract, + // as it will elliminate the need to check for negative scores + it("should strengthen the villain if they are fighting their nemesis", async () => { + // Arrange + getCharacters.mockResolvedValue({ + items: [ + { name: "Superman", score: 8, type: "hero", weakness: "Lex Luthor" }, + { name: "Lex Luthor", score: 8, type: "villain" } + ] + }); + + // Act + const result = await battle("Superman", "Lex Luthor"); + + // Assert + expect(result).toHaveProperty("name", "Lex Luthor"); + expect(result).toHaveProperty("score", 9.0); + }); + + it("should strengthen the hero if they are fighting their nemesis", async () => { + // Arrange + getCharacters.mockResolvedValue({ + items: [ + { name: "Batman", score: 8, type: "hero", weakness: "Joker" }, + { name: "Joker", score: 8, type: "villain" } + ] + }); + + // Act + const result = await battle("Batman", "Joker"); + + // Assert + expect(result).toHaveProperty("name", "Joker"); + expect(result).toHaveProperty("score", 9.0); + }); + + it("should have names registry sensitive", async () => { + // Arrange + getCharacters.mockResolvedValue({ + items: [ + { name: "Loser", score: 8.0, type: "hero" }, + { name: "Winner", score: 9.0, type: "villain" } + ] + }); + + // Act/Assert + await expect(battle("loser", "Winner")).rejects.toThrow( + "failed to find characters" + ); + await expect(battle("Loser", "winner")).rejects.toThrow( + "failed to find characters" + ); + }); +}); diff --git a/src/getCharacters.js b/src/getCharacters.js index 3dbc683..ad980b8 100644 --- a/src/getCharacters.js +++ b/src/getCharacters.js @@ -1,5 +1,17 @@ -function getCharacters() { - throw new Error("Not implemented") +const axios = require("axios"); + +const charactersUrl = + "https://s3.eu-west-2.amazonaws.com/build-circle/characters.json"; + +async function getCharacters() { + try { + const res = await axios.get(charactersUrl); + // No need to check for status code, axios will throw an error if it's not 200 + + return res.data.items; + } catch (error) { + throw new Error("failed to fetch characters"); + } } -module.exports = getCharacters; \ No newline at end of file +module.exports = getCharacters; diff --git a/src/getCharacters.spec.js b/src/getCharacters.spec.js new file mode 100644 index 0000000..30f0c35 --- /dev/null +++ b/src/getCharacters.spec.js @@ -0,0 +1,76 @@ +const getCharacters = require("./getCharacters"); +const nock = require("nock"); + +const testCaracter = { + name: "Batman", + score: 8.3, + type: "hero", + weakness: "Joker" +}; + +describe("getCharacters", () => { + beforeEach(() => { + nock.cleanAll(); + }); + + it("should return an array of characters", async () => { + // Arrange + nock("https://s3.eu-west-2.amazonaws.com") + .get("/build-circle/characters.json") + .reply(200, { items: [testCaracter] }); + + // Act + const result = await getCharacters(); + + // Assert + expect(Array.isArray(result)).toBe(true); + }); + + it("should return an array of characters with the correct properties", async () => { + // Arrange + nock("https://s3.eu-west-2.amazonaws.com") + .get("/build-circle/characters.json") + .reply(200, { items: [testCaracter] }); + + // Act + const result = await getCharacters(); + + // Assert + expect(result).toEqual( + expect.arrayContaining([ + expect.objectContaining({ + name: expect.any(String), + score: expect.any(Number), + type: expect.any(String), + weakness: expect.any(String) + }) + ]) + ); + }); + + it("should handle 500 http errors", async () => { + // Arrange + nock("https://s3.eu-west-2.amazonaws.com") + .get("/build-circle/characters.json") + .reply(500); + + // Act + const result = getCharacters(); + + // Assert + await expect(result).rejects.toThrow("failed to fetch characters"); + }); + + it("should handle 404 http errors", async () => { + // Arrange + nock("https://s3.eu-west-2.amazonaws.com") + .get("/build-circle/characters.json") + .reply(404); + + // Act + const result = getCharacters(); + + // Assert + await expect(result).rejects.toThrow("failed to fetch characters"); + }); +}); diff --git a/src/index.js b/src/index.js index c0ea687..5d538a4 100644 --- a/src/index.js +++ b/src/index.js @@ -1,10 +1,18 @@ -const express = require('express'); -const battle = require('./battle'); +const express = require("express"); +const battle = require("./battle"); const app = express(); -app.get('/battle', (req, res) => { - const result = battle(req.query.hero, req.query.villain) +app.get("/battle", async (req, res) => { + const { hero, villain } = req.query; + + if (!hero || !villain) { + res.status(400).send("hero and villain are required"); + return; + } + + const result = await battle(hero, villain); + res.send(result); }); diff --git a/src/index.spec.js b/src/index.spec.js index bac2bfb..2a6a847 100644 --- a/src/index.spec.js +++ b/src/index.spec.js @@ -1,10 +1,26 @@ -const request = require("supertest") -const app = require("./index") +const request = require("supertest"); +const app = require("./index"); +const getCharacters = require("./getCharacters"); + +jest.mock("./getCharacters"); describe("GET /battle", () => { it("should return 200", async () => { - const response = await request(app).get("/battle?hero=Batman&villain=Joker"); + // Arrange + getCharacters.mockResolvedValue({ + items: [ + { name: "Batman", score: 9.0, type: "hero" }, + { name: "Joker", score: 8.0, type: "villain" } + ] + }); + + // Act + const response = await request(app).get( + "/battle?hero=Batman&villain=Joker" + ); + // Assert expect(response.statusCode).toBe(200); + expect(response.body).toEqual({ name: "Batman", score: 9.0, type: "hero" }); }); -}); \ No newline at end of file +});