27
loading...
This website collects cookies to deliver better user experience
mkdir node-organize
npm init -y
to install node packages. Not required for using modules, but we are going to use node-fetch
.cd node-organize
npm init -y
node-fetch
or axios
to make fetch requests.npm install node-fetch
services.js
file, which holds the reusable code blocks.touch services.js
// import fetch
const fetch = require('node-fetch');
// best practice to use constants for URLs
const URL = 'https://jsonplaceholder.typicode.com/todos';
/*
interface TodoItem {
userId: number;
id: number;
title: string;
completed: boolean;
}
Todos: Array<TodoItem>
*/
// fetch all todos and decode response as json
function getAllTodos() {
return fetch(URL)
.then(response => response.json())
.then(todos => todos)
.catch(err => console.err(err));
}
// filter todos
function filterCompleted(todos, completed) {
return todos.filter(i => i.completed === completed);
}
// filter todos per user id
function filterPerUserId(todos, id) {
return todos.filter(i => i.userId === id);
}
module.exports
object with a new object containing the functions from services.js
.module.exports = {
getAllTodos,
filterPerUserId,
filterCompleted,
};
index.js
file, which will import the modules.touch index.js
const {
getAllTodos,
filterCompleted,
filterPerUserId,
} = require('./services');
// getAllTodos returns a Promise
getAllTodos().then(todos => {
const completed = filterCompleted(todos, true);
const userCompletedTodos = filterPerUserId(completed, 10);
console.log(userCompletedTodos);
});
node index.js
and should see the todos as output in the console.