Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Sorting, filters, search and form validation #6

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -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
29 changes: 15 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
300 changes: 300 additions & 0 deletions app.js
Original file line number Diff line number Diff line change
@@ -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,
}) => `
<div class="card mb-3 video-request" data-id="${_id}">
<div class="card-body d-flex justify-content-between flex-row">
<div class="d-flex flex-column">
<h3 class="video-request__topic">${topic_title}</h3>
<p class="text-muted mb-2" class="video-request__topic-details">${
topic_details || "N/A"
}</p>
<strong>Expected results:</strong>
<p class="mb-0 text-muted" class="video-request__expected-result">${
expected_result || "N/A"
}</p>
</div>
<div class="d-flex flex-column text-center">
<button type="button" class="btn btn-link" onClick="app.onRequestVote('ups', '${_id}')">🔺</button>
<h3 class="video-request__votes">${votes.voting}</h3>
<button type="button" class="btn btn-link" onClick="app.onRequestVote('downs', '${_id}')">🔻</button>
</div>
</div>
<div class="card-footer d-flex flex-row justify-content-between">
<div>
<span class="text-info" class="video-request__status">${status.toUpperCase()}</span>
&bullet; added by <strong class="video-request__by" title="${author_email}">${author_name}</strong> on
<strong class="video-request__at">${app.datePipe(
submit_date
)}</strong>
</div>

<div class="d-flex justify-content-center flex-column 408ml-auto mr-2">
<div class="badge badge-success" class="video-request__level">${target_level}</div>
</div>

<button type="button" class="btn btn-danger" onClick="app.onRequestDelete(event, '${_id}')">
<svg class="bi bi-trash-fill" width="1em" height="1em" viewBox="0 0 16 16" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path fill-rule="evenodd" d="M2.5 1a1 1 0 00-1 1v1a1 1 0 001 1H3v9a2 2 0 002 2h6a2 2 0 002-2V4h.5a1 1 0 001-1V2a1 1 0 00-1-1H10a1 1 0 00-1-1H7a1 1 0 00-1 1H2.5zm3 4a.5.5 0 01.5.5v7a.5.5 0 01-1 0v-7a.5.5 0 01.5-.5zM8 5a.5.5 0 01.5.5v7a.5.5 0 01-1 0v-7A.5.5 0 018 5zm3 .5a.5.5 0 00-1 0v7a.5.5 0 001 0v-7z" clip-rule="evenodd"/>
</svg>
</button>
</div>
</div>
`;

// 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
});
})();
Loading