diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..db6f34c --- /dev/null +++ b/.editorconfig @@ -0,0 +1,14 @@ +root = true + +[*] +indent_style = space +indent_size = 2 +charset = utf-8 +trim_trailing_whitespace = true +insert_final_newline = true +end_of_line = lf +# editorconfig-tools is unable to ignore longs strings or urls +max_line_length = off + +[CHANGELOG.md] +indent_size = false diff --git a/README.md b/README.md index 55f08a6..4f6797e 100644 --- a/README.md +++ b/README.md @@ -2,26 +2,27 @@ > Hi all, this is the repo that holds the assessments that covers ramadan 2020 series on [Semicolon academy](https://www.youtube.com/SemicolonAcademy) youtube channel, no implementations here, only the assessments, you could check later the resolutions on different repos on github as well, or watch the series and build it up together. -In this repo you will find some given express server configured to make some basic CRUD operations for getting and setting a video request from semicolon academy (as an example), also you will find an HTML file that has basic design of the required elements styled as well with twitter bootstrap, you only need to clone it and install dependancies of server and configure a local mongodb connection, then you are ready to make your first assessment, goodluck 😉 +In this repo you will find some given express server configured to make some basic CRUD operations for getting and setting a video request from semicolon academy (as an example), also you will find an HTML file that has basic design of the required elements styled as well with twitter bootstrap, you only need to clone it and install dependencies of server and configure a local mongodb connection, then you are ready to make your first assessment, good luck 😉 --- ## Assessment 1 (Junior level friendly) -1. After cloning the repo and installing the dependancies in the server folder, you should next [setup mongodb](https://docs.mongodb.com/manual/installation/) locally and copy the connection url to the required place in `server/models/mongo.config.js` then run `npm start` in the server folder (btw, cors are enabled so you can run server if you want on a separate port). -2. Implement the frontend code to make it work with the following functionalities: - - [ ] Submit a video request. (API: POST -> `/video-request`) - - [ ] Show list of requests below the form. (API: GET -> `/video-request`) - - [ ] Vote up and down on each request. (API: PUT -> `/video-request/vote`) - - [ ] Sorting options `new first` the default one, and `top voted first`. - - [ ] Search box to search for vide requests. - - [ ] Client-side validation for the fields with * as required and for the email field, topic title should be max 100 length. +1. After cloning the repo and installing the dependencies in the server folder, you should next [setup mongodb](https://docs.mongodb.com/manual/installation/) locally and copy the connection url to the required place in `server/models/mongo.config.js`. +2. Navigate to server directory, run `npm install` then run `npm start` in the server folder (btw, cors are enabled so you can run server if you want on a separate port). +3. Implement the frontend code to make it work with the following functionalities: + - [x] Submit a video request. (API: POST -> `/video-request`) + - [x] Show list of requests below the form. (API: GET -> `/video-request`) + - [x] Vote up and down on each request. (API: PUT -> `/video-request/vote`) + - [x] Sorting options `new first` the default one, and `top voted first`. + - [x] Search box to search for vide requests. + - [x] Client-side validation for the fields with * as required and for the email field, topic title should be max 100 length. - [ ] Add signup/login form with email. - [ ] Make votes unique so no one could cheat, using unique user, enhance the voting experience. - [ ] Make a super user capabilities, delete, add resolution video, and change status. all are only visible to him. - [ ] Add style to the super user capabilities and make filter by request statuses (`NEW`, `PLANNED`, `DONE`). -3. Feel free to enhance the APIs to suit your needs if needed. -4. You are supposed after all to make the requests work using AJAX to make the project looks like a SPA. -5. Check all payloads in the schema at `server/models/video-requests.model.js` and check the endpoints at `server/index.js` -6. You are **obligated** to write only **pure JavaScript** code without using any external utility or libraries. -7. You should not write any css code or styling effort as the provided `index.html` file has almost all what you need, but you can use the bootstrap provided classes. +4. Feel free to enhance the APIs to suit your needs if needed. +5. You are supposed after all to make the requests work using AJAX to make the project looks like a SPA. +6. Check all payloads in the schema at `server/models/video-requests.model.js` and check the endpoints at `server/index.js` +7. You are **obligated** to write only **pure JavaScript** code without using any external utility or libraries. +8. You should not write any css code or styling effort as the provided `index.html` file has almost all what you need, but you can use the bootstrap provided classes. diff --git a/app.js b/app.js new file mode 100644 index 0000000..d85c6c7 --- /dev/null +++ b/app.js @@ -0,0 +1,300 @@ +(() => { + "use strict"; + + document.addEventListener("DOMContentLoaded", (event) => { + // app global scope + const app = (window.app = window.app || {}); + + // configs + let apiHost = "http://localhost:7777"; + let api = { + postVideoRequest: `${apiHost}/video-request`, + getVideoRequests: `${apiHost}/video-request`, + deleteVideoRequest: `${apiHost}/video-request`, + voteOnRequest: `${apiHost}/video-request/vote`, + }; + + // app state + let state = { + videoRequest: [], + sortBy: "", + }; + + function setState(reducer = () => state) { + const stateChange = reducer(state); + console.log("state change ===========", stateChange); + Object.assign(state, stateChange); + onStateChange(stateChange); + } + + const requestsListContainerElement = document.querySelector( + "#listOfRequests" + ); + + const requestEmptyState = () => { + const template = document.querySelector( + "template.video-request--empty-state" + ); + return template.innerHTML; + }; + + const filtersElement = document.querySelector(".filters"); + const sortingHtmlInputs = filtersElement.querySelectorAll( + "input[name=sort]" + ); + + const buildVideoRequestHtml = ({ + _id, + author_name, + author_email, + status, + submit_date, + topic_title, + expected_result, + target_level, + topic_details, + update_date, + video_ref, + votes, + }) => ` +
+
+
+

${topic_title}

+

${ + topic_details || "N/A" + }

+ Expected results: +

${ + expected_result || "N/A" + }

+
+
+ +

${votes.voting}

+ +
+
+ +
+ `; + + // set initial state + setState(() => { + return { + videoRequest: [], + sortBy: "submit_date", + }; + }); + + // compose HTML for video requests + function composeVideoRequestsListHtml(data = []) { + return data.length + ? data.map((item) => buildVideoRequestHtml(item)).join("") + : requestEmptyState(); + } + + // render requests + function renderList() { + requestsListContainerElement.innerHTML = composeVideoRequestsListHtml( + state.videoRequest + ); + } + + // render updated voting + function renderRequest(requestData, action) { + if (!requestData) return; + + const targetElement = document.querySelector( + `.video-request[data-id='${requestData._id}']` + ); + + action === "DELETE" + ? targetElement.remove() + : (targetElement.outerHTML = buildVideoRequestHtml(requestData)); + } + + // submit single video request + function submitVideoRequest(payload, onSuccess, onError) { + fetch(api.postVideoRequest, { + method: "POST", + body: payload, + }) + .then((response) => response.json()) + .then(onSuccess) + .catch(onError); + } + + // get video requests + function getVideoRequests(queryParams = {}) { + let params; + + if (Object.entries(queryParams).length) { + params = toQueryString(queryParams); + } + + const requestUrl = params + ? `${api.getVideoRequests}${params}` + : api.getVideoRequests; + + fetch(requestUrl) + .then((response) => response.json()) + .then((data) => { + setState(() => { + return { videoRequest: data }; + }); + renderList(); + }) + .catch((error) => { + console.error("GET Error:", error); + }); + } + + // delete request by ID + function deleteVideoRequest(id, onSuccess, onError) { + fetch(api.deleteVideoRequest, { + method: "DELETE", + headers: { "content-Type": "application/json" }, + body: JSON.stringify({ id }), + }) + .then((response) => response.json()) + .then(onSuccess) + .catch(onError); + } + + // Vote on a video request + function voteOnRequest( + { requestID: id, VoteType: vote_type }, + onSuccess, + onError + ) { + fetch(api.voteOnRequest, { + method: "PUT", + headers: { "content-Type": "application/json" }, + body: JSON.stringify({ id, vote_type }), + }) + .then((response) => response.json()) + .then(onSuccess) + .catch(onError); + } + + function toQueryString(object) { + return ( + "?" + + Object.keys(object) + .map((key) => `${key}=${object[key].toString()}`) + .join("&") + ); + } + + app.onRequestSubmit = (event) => { + event.preventDefault(); + const form = event.target; + + submitVideoRequest( + new FormData(form), + () => { + getVideoRequests(); + form.reset(); + }, + console.log + ); + }; + + app.onRequestDelete = (event, requestID) => { + if (!requestID) return; + event.preventDefault(); + deleteVideoRequest( + requestID, + (res) => { + renderRequest({ _id: requestID }, "DELETE"); + }, + console.log + ); + }; + + app.onRequestVote = (VoteType = "ups" || "downs", requestID) => { + if (!requestID) return; + voteOnRequest({ requestID, VoteType }, renderRequest, console.log); + }; + + app.datePipe = (date) => { + const options = { + weekday: "long", + year: "numeric", + month: "long", + day: "numeric", + }; + return new Date(date).toLocaleDateString("en-US", options); + }; + + app.onSearch = ({ target }) => { + target.value.length > 2 && + getVideoRequests({ topic_title: target.value }); + }; + + app.sort = (event) => { + const { target } = event; + + if (target.type !== "radio") { + target.classList.contains("active") && event.preventDefault(); + return; + } + + let { value } = target; + + // call set state only on value change + if ( + (value === "voting" || value === "submit_date") && + state.sortBy !== value + ) { + setState(() => { + return { sortBy: value }; + }); + } + }; + + // on state change + function onStateChange(stateChange = { ...state }) { + if (stateChange.sortBy) { + // toggle active state - render - dom changes + sortingHtmlInputs.forEach((node) => { + if (node.value === stateChange.sortBy) { + node.offsetParent.classList.add("active"); + } else { + node.offsetParent.classList.remove("active"); + } + }); + + // sorting API call + const query = { + sortBy: + stateChange.sortBy === "voting" + ? stateChange.sortBy + : "submit_date", + }; + + getVideoRequests(query); + } + } + // end + }); +})(); diff --git a/index.html b/index.html index cf38103..e3cf38d 100644 --- a/index.html +++ b/index.html @@ -11,13 +11,14 @@
-
-
+
+
@@ -41,8 +45,11 @@
@@ -67,6 +74,7 @@