From 1e76e666b96929500de6dda5489964dd1774a94c Mon Sep 17 00:00:00 2001 From: azharimm Date: Sun, 5 Sep 2021 07:26:26 +0700 Subject: [PATCH] add: latest phone endpoint --- src/controllers/v2/index.js | 4 ++++ src/controllers/v2/miscController.js | 34 ++++++++++++++++++++++++++++ src/routes/v2/index.js | 2 ++ 3 files changed, 40 insertions(+) create mode 100644 src/controllers/v2/miscController.js diff --git a/src/controllers/v2/index.js b/src/controllers/v2/index.js index 6fe5bb9..54d846d 100644 --- a/src/controllers/v2/index.js +++ b/src/controllers/v2/index.js @@ -22,5 +22,9 @@ exports.index = (req, res) => { endpoint: '/v2/search', example: fullUrl+'/search?query=Iphone 12 pro max' }, + latest: { + endpoint: '/v2/latest', + example: fullUrl+'/latest' + }, }); } diff --git a/src/controllers/v2/miscController.js b/src/controllers/v2/miscController.js new file mode 100644 index 0000000..db15718 --- /dev/null +++ b/src/controllers/v2/miscController.js @@ -0,0 +1,34 @@ +const request = require("request-promise"); +const cheerio = require("cheerio"); +const { json, errorJson } = require("../../utils/response"); + +exports.index = async (req, res) => { + try { + const url = `${process.env.BASE_URL}`; + const htmlResult = await request.get(url); + const $ = await cheerio.load(htmlResult); + const title = "Latest Devices"; + const phones = []; + $(".module-latest") + .find("a") + .each((index, el) => { + const phone_name = $(el).text(); + const image = $(el).find("img").attr("src"); + const slug = $(el).attr("href").replace(".php", ""); + phones.push({ + phone_name, + slug, + image, + detail: + req.protocol + "://" + req.get("host") + "/v2/" + slug, + }); + }); + + return json(res, { + title, + phones, + }); + } catch (error) { + return errorJson(res, error); + } +}; diff --git a/src/routes/v2/index.js b/src/routes/v2/index.js index e33ed2e..f8f46f9 100644 --- a/src/routes/v2/index.js +++ b/src/routes/v2/index.js @@ -6,11 +6,13 @@ const indexController = require('../../controllers/v2/index') const brandController = require('../../controllers/v2/brandController') const specController = require('../../controllers/v2/specController') const searchController = require('../../controllers/v2/searchController') +const miscController = require('../../controllers/v2/miscController') router.get("/", indexController.index); router.get("/brands", brandController.index); router.get("/brands/:slug", brandController.show); router.get("/search", searchController.index); +router.get("/latest", miscController.index); router.get("/:slug", specController.index); module.exports = router;