كيفية إنشاء تطبيق Todo باستخدام React و TypeScript و NodeJS و MongoDB

في هذا البرنامج التعليمي ، سنستخدم TypeScript على كلا الجانبين (الخادم والعميل) لبناء تطبيق Todo من البداية باستخدام React و NodeJS و Express و MongoDB.

لذا ، لنبدأ بالتخطيط لواجهة برمجة التطبيقات.

  • API مع NodeJS و Express و MongoDB و TypeScript
  • اعداد
  • قم بإنشاء نوع Todo
  • قم بإنشاء نموذج Todo
  • إنشاء وحدات تحكم API
  • الحصول على Todos وإضافتها وتحديثها وحذفها
  • إنشاء مسارات API
  • قم بإنشاء خادم
  • جانب العميل مع React و TypeScript
  • اعداد
  • قم بإنشاء نوع Todo
  • إحضار البيانات من API
  • قم بإنشاء المكونات
  • أضف نموذج تودو
  • اعرض ملف Todo
  • إحضار وعرض البيانات
  • مصادر

دعنا نتعمق.

API مع NodeJS و Express و MongoDB و TypeScript

جاري الإعداد

إذا كنت جديدًا على هذا ، فيمكنك البدء بدليل عملي لـ TypeScript أو كيفية إنشاء واجهة برمجة تطبيقات من البداية باستخدام Node JS و Express و MongoDB لتحقيق أقصى استفادة من هذا البرنامج التعليمي. وإلا فلنبدأ.

لإنشاء تطبيق NodeJS جديد ، تحتاج إلى تشغيل هذا الأمر على الجهاز:

 yarn init 

سيطلب منك بضعة أسئلة ثم يقوم بتهيئة التطبيق. يمكنك تخطيه عن طريق إضافة -yعلم إلى الأمر.

بعد ذلك ، هيكل المشروع على النحو التالي:

├── dist ├── node_modules ├── src ├── app.ts ├── controllers | └── todos | └── index.ts ├── models | └── todo.ts ├── routes | └── index.ts └── types └── todo.ts ├── nodemon.json ├── package.json ├── tsconfig.json 

كما ترى ، بنية الملف هذه بسيطة نسبيًا. و distسوف الدليل بمثابة المجلد الإخراج بمجرد تجميع رمز إلى عادي جافا سكريبت.

لدينا أيضًا app.tsملف يمثل نقطة دخول الخادم. وحدات التحكم والأنواع والمسارات موجودة أيضًا في أسماء المجلدات الخاصة بها.

الآن ، نحتاج إلى تكوين tsconfig.jsonالملف لمساعدة المترجم على متابعة تفضيلاتنا.

  • tsconfig.json
{ "compilerOptions": { "target": "es6", "module": "commonjs", "outDir": "dist/js", "rootDir": "src", "strict": true, "esModuleInterop": true, "forceConsistentCasingInFileNames": true }, "include": ["src/**/*"], "exclude": ["src/types/*.ts", "node_modules", ".vscode"] } 

هنا لدينا أربع خصائص رئيسية للتأكيد عليها:

outDir: يخبر المترجم بوضع الكود المترجم في dist/jsالمجلد.

rootDir: يُعلم TypeScript بتجميع كل .tsملف موجود في srcالمجلد.

include: يخبر المترجم بتضمين الملفات الموجودة في srcالدليل والمجلد الفرعي.

exclude: سيستبعد الملفات أو المجلدات التي تم تمريرها في المصفوفة أثناء وقت الترجمة.

يمكننا الآن تثبيت التبعيات لتمكين TypeScript في المشروع. لأنه افتراضيًا ، سيستخدم هذا التطبيق JavaScript.

هناك طريقتان لاستخدام TypeScript في تطبيق NodeJS. إما محليًا في المشروع أو عالميًا في أجهزتنا. سأختار الأخير بناءً على التفضيل الشخصي ، ولكن يمكنك التمسك بالطريقة المحلية إذا كنت تريد أيضًا.

الآن ، دعنا ننفذ الأمر التالي على الجهاز لتثبيت TypeScript.

 yarn add typescript -g 

gتسمح هذه العلامة بتثبيت TypeScript عالميًا وهذا يجعله متاحًا من أي مكان على الكمبيوتر.

بعد ذلك ، دعنا نضيف بعض التبعيات من أجل استخدام Express و MongoDB.

 yarn add express cors mongoose 

نحتاج أيضًا إلى تثبيت أنواعها كاعتماديات تطوير لمساعدة مترجم TypeScript على فهم الحزم.

 yarn add -D @types/node @types/express @types/mongoose @types/cors 

الآن ، لن يصرخ TypeScript عليك بعد الآن - سيستخدم هذه الأنواع لتحديد المكتبات التي قمنا بتثبيتها للتو.

نحتاج أيضًا إلى إضافة تبعيات أخرى حتى نتمكن من تجميع كود TypeScript وبدء الخادم في نفس الوقت.

 yarn add -D concurrently nodemon 

مع ذلك ، يمكننا الآن تحديث package.jsonالملف بالبرامج النصية اللازمة لبدء الخادم.

  • package.json
 "scripts": { "build": "tsc", "start": "concurrently \"tsc -w\" \"nodemon dist/js/app.js\"" } 

concurrentlyسيساعد في تجميع شفرة TypeScript ، ومتابعة التغييرات ، وكذلك بدء تشغيل الخادم في وقت واحد. ومع ذلك ، يمكننا الآن تشغيل الخادم - ومع ذلك ، لم نخلق شيئًا ذا مغزى بعد في هذا الصدد. لذا ، دعنا نصلح ذلك في القسم التالي.

قم بإنشاء نوع Todo

  • أنواع / todo.ts
import { Document } from "mongoose" export interface ITodo extends Document { name: string description: string status: boolean } 

Here, we have a Todo interface that extends the Document type provided by mongoose. We will be using it later to interact with MongoDB. That said, we can now define how a Todo model should look.

Create a Todo Model

  • models/todo.ts
import { ITodo } from "./../types/todo" import { model, Schema } from "mongoose" const todoSchema: Schema = new Schema( { name: { type: String, required: true, }, description: { type: String, required: true, }, status: { type: Boolean, required: true, }, }, { timestamps: true } ) export default model("Todo", todoSchema) 

As you can see here, we start by importing the interface ITodo and some utilities from mongoose. The latter helps to define the Todo schema and also pass in ITodo as a type to the model before exporting it.

With that, we can now use the Todo model in other files to interact with the database.

Create API controllers

Get, Add, Update and Delete Todos

  • controllers/todos/index.ts
import { Response, Request } from "express" import { ITodo } from "./../../types/todo" import Todo from "../../models/todo" const getTodos = async (req: Request, res: Response): Promise => { try { const todos: ITodo[] = await Todo.find() res.status(200).json({ todos }) } catch (error) { throw error } } 

Here, we first need to import some types from express because I want to type the values explicitly. If you want, you can let TypeScript infer it for you.

Next, we use the function getTodos() to fetch data. It receives a req and res parameter and returns a promise.

And with the help of the Todo model created earlier, we can now get data from MongoDB and return a response with the array of todos.

  • controllers/todos/index.ts
const addTodo = async (req: Request, res: Response): Promise => { try { const body = req.body as Pick const todo: ITodo = new Todo({ name: body.name, description: body.description, status: body.status, }) const newTodo: ITodo = await todo.save() const allTodos: ITodo[] = await Todo.find() res .status(201) .json({ message: "Todo added", todo: newTodo, todos: allTodos }) } catch (error) { throw error } } 

As you can see, the function addTodo() receives the body object that contains data entered by the user.

Next, I use typecasting to avoid typos and restrict the body variable to match ITodo and then create a new Todo based on the model.

With that in place, we can now save the Todo in the DB and return a response that contains the todo created and the updated todos array.

  • controllers/todos/index.ts
const updateTodo = async (req: Request, res: Response): Promise => { try { const { params: { id }, body, } = req const updateTodo: ITodo | null = await Todo.findByIdAndUpdate( { _id: id }, body ) const allTodos: ITodo[] = await Todo.find() res.status(200).json({ message: "Todo updated", todo: updateTodo, todos: allTodos, }) } catch (error) { throw error } } 

To update a todo, we need to extract the id and the body from the req object and then pass them to findByIdAndUpdate(). This utility will find the Todo on the database and update it. And once the operation is completed, we can now return the updated data to the user.

  • controllers/todos/index.ts
const deleteTodo = async (req: Request, res: Response): Promise => { try { const deletedTodo: ITodo | null = await Todo.findByIdAndRemove( req.params.id ) const allTodos: ITodo[] = await Todo.find() res.status(200).json({ message: "Todo deleted", todo: deletedTodo, todos: allTodos, }) } catch (error) { throw error } } export { getTodos, addTodo, updateTodo, deleteTodo } 

The function deleteTodo() allows you to delete a Todo from the database. Here, we pull out the id from req and pass it as an argument to findByIdAndRemove() to access the corresponding Todo and delete it from the DB.

Next, we export the functions to be able to use them in other files. That said, we can now create some routes for the API and use these methods to handle the requests.

Create API routes

  • routes/index.ts
import { Router } from "express" import { getTodos, addTodo, updateTodo, deleteTodo } from "../controllers/todos" const router: Router = Router() router.get("/todos", getTodos) router.post("/add-todo", addTodo) router.put("/edit-todo/:id", updateTodo) router.delete("/delete-todo/:id", deleteTodo) export default router 

As you can see here, we have four routes to get, add, update, and delete todos from the database. And since we already created the functions, the only thing we have to do is import the methods and pass them as parameters to handle the requests.

So far, we have covered a lot. But we still don't have a server to start. So, let's fix that in the next section.

Create a Server

Before creating the server, we need to first add some environment variables that will hold the MongoDB credentials in the nodemon.json file.

  • nodemon.json
{ "env": { "MONGO_USER": "your-username", "MONGO_PASSWORD": "your-password", "MONGO_DB": "your-db-name" } } 

You can get the credentials by creating a new cluster on MongoDB Atlas.

  • app.ts
import express, { Express } from "express" import mongoose from "mongoose" import cors from "cors" import todoRoutes from "./routes" const app: Express = express() const PORT: string | number = process.env.PORT || 4000 app.use(cors()) app.use(todoRoutes) const uri: string = `mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASSWORD}@clustertodo.raz9g.mongodb.net/${process.env.MONGO_DB}?retryWrites=true&w=majority` const options = { useNewUrlParser: true, useUnifiedTopology: true } mongoose.set("useFindAndModify", false) mongoose .connect(uri, options) .then(() => app.listen(PORT, () => console.log(`Server running on //localhost:${PORT}`) ) ) .catch(error => { throw error }) 

Here, we start by importing the express library that allows us to access the use() method that helps handle the Todos routes.

Next, we use the mongoose package to connect to MongoDB by appending to the URL the credentials held on the nodemon.json file.

That said, now if we connect successfully to MongoDB, the server will start. If appropriate, an error will be thrown.

We're now done building the API with Node, Express, TypeScript, and MongoDB. Let's now start building the client-side app with React and TypeScript.

فرح

Client-side with React and TypeScript

Setting up

To create a new React app, I will go with create-react-app - you can use other methods as well if you want.

So, let's run in the terminal the following command:

 npx create-react-app my-app --template typescript 

Next, install the Axios library to be able to fetch remote data.

 yarn add axios 

Once the installation completed, let's structure our project as follows:

├── node_modules ├── public ├── src | ├── API.ts | ├── App.test.tsx | ├── App.tsx | ├── components | | ├── AddTodo.tsx | | └── TodoItem.tsx | ├── index.css | ├── index.tsx | ├── react-app-env.d.ts | ├── setupTests.ts | └── type.d.ts ├── tsconfig.json ├── package.json └── yarn.lock 

Here, we have a relatively simple file structure. The main thing to notice is that src/type.d.ts will hold the types. And since I will use them on almost every file, I added the extension .d.ts to make the types globally available. And now we don't need to import them anymore.

Create a Todo Type

  • src/type.d.ts
interface ITodo { _id: string name: string description: string status: boolean createdAt?: string updatedAt?: string } interface TodoProps { todo: ITodo } type ApiDataType = { message: string status: string todos: ITodo[] todo?: ITodo } 

Here, the ITodo interface needs to mirror the shape of data from the API. And since we don't have mongoose here, we need to add additional properties to match the type defined on the API.

Next, we use that same interface for the TodoProps which is the type annotation for the props that will be received by the component responsible for rendering the data.

We have now defined our types - let's now start fetching data from the API.

Fetch data from the API

  • src/API.ts
import axios, { AxiosResponse } from "axios" const baseUrl: string = "//localhost:4000" export const getTodos = async (): Promise
    
      => { try { const todos: AxiosResponse = await axios.get( baseUrl + "/todos" ) return todos } catch (error) { throw new Error(error) } } 
    

As you can see, we need to import axios to request data from the API. Next, we use the function getTodos() to get data from the server. It will return a promise of type AxiosResponse that holds the Todos fetched that need to match the type ApiDataType.

  • src/API.ts
export const addTodo = async ( formData: ITodo ): Promise
    
      => { try { const todo: Omit = { name: formData.name, description: formData.description, status: false, } const saveTodo: AxiosResponse = await axios.post( baseUrl + "/add-todo", todo ) return saveTodo } catch (error) { throw new Error(error) } } 
    

This function receives the data entered by the user as an argument and returns a promise. Here, we need to omit the _id property because MongoDB will create it on the fly.

  • src/API.ts
export const updateTodo = async ( todo: ITodo ): Promise
    
      => { try { const todoUpdate: Pick = { status: true, } const updatedTodo: AxiosResponse = await axios.put( `${baseUrl}/edit-todo/${todo._id}`, todoUpdate ) return updatedTodo } catch (error) { throw new Error(error) } } 
    

To update a Todo, we have to pass in the updated data and the _id of the object. Here, we need to change the status of the Todo, which is why I only pick the property we need before sending the request to the server.

  • src/API.ts
export const deleteTodo = async ( _id: string ): Promise
    
      => { try { const deletedTodo: AxiosResponse = await axios.delete( `${baseUrl}/delete-todo/${_id}` ) return deletedTodo } catch (error) { throw new Error(error) } } 
    

Here, we also have a function that receives as a parameter the _id property and returns a promise.

With that in place, we can now go to the components folder and add some meaningful code to its files.

Create the components

Add Todo Form

  • components/AddTodo.tsx
import React from "react" type Props = TodoProps & { updateTodo: (todo: ITodo) => void deleteTodo: (_id: string) => void } const Todo: React.FC = ({ todo, updateTodo, deleteTodo }) => { const checkTodo: string = todo.status ? `line-through` : "" return ( 

{todo.name}

{todo.description} updateTodo(todo)} className={todo.status ? `hide-button` : "Card--button__done"} > Complete deleteTodo(todo._id)} className="Card--button__delete" > Delete ) } export default Todo

As you can see, here we have a functional component of type React.FC (FC stands for functional component). It receives as a prop the method saveTodo() that allows us to save data to the DB.

Next, we have a formData state that needs to match the ITodo type to satisfy the compiler. That is why we pass it to the useState hook. We also need to add an alternative type ({}) because the initial state will be an empty object.

And with that, we can now move forward and display the data fetched.

Display a Todo

  • components/TodoItem.tsx
import React from "react" type Props = TodoProps & { updateTodo: (todo: ITodo) => void deleteTodo: (_id: string) => void } const Todo: React.FC = ({ todo, updateTodo, deleteTodo }) => { const checkTodo: string = todo.status ? `line-through` : "" return ( 

{todo.name}

{todo.description} updateTodo(todo)} className={todo.status ? `hide-button` : "Card--button__done"} > Complete deleteTodo(todo._id)} className="Card--button__delete" > Delete ) } export default Todo

Here, we need to extend the TodoProps type and append the functions updateTodo and deleteTodo to handle appropriately the props received by the component.

Now, once the Todo object passed in, we will be able to display it and add the functions needed to update or delete a Todo.

Great! We can now go to the App.tsx file and add the last piece to the puzzle.

Fetch and Display data

  • App.tsx
import React, { useEffect, useState } from 'react' import TodoItem from './components/TodoItem' import AddTodo from './components/AddTodo' import { getTodos, addTodo, updateTodo, deleteTodo } from './API' const App: React.FC = () => { const [todos, setTodos] = useState([]) useEffect(() => { fetchTodos() }, []) const fetchTodos = (): void => { getTodos() .then(({ data: { todos } }: ITodo[] | any) => setTodos(todos)) .catch((err: Error) => console.log(err)) } 

Here, we first need to import the components and utility functions held on API.ts. Next, we pass to useState an array of type ITodo and initialize it with an empty array.

The method getTodos() returns a promise - therefore, we can access the then function and update the state with the data fetched or throw an error if any occurs.

With that in place, we can now call the function fetchTodos() when the component is successfully mounted.

  • App.tsx
const handleSaveTodo = (e: React.FormEvent, formData: ITodo): void => { e.preventDefault() addTodo(formData) .then(({ status, data }) => { if (status !== 201) { throw new Error("Error! Todo not saved") } setTodos(data.todos) }) .catch(err => console.log(err)) } 

Once the form is submitted, we use addTodo() to send the request to the server, and then if the Todo has successfully saved, we update the data, otherwise an error will be thrown.

  • App.tsx
const handleUpdateTodo = (todo: ITodo): void => { updateTodo(todo) .then(({ status, data }) => { if (status !== 200) { throw new Error("Error! Todo not updated") } setTodos(data.todos) }) .catch(err => console.log(err)) } const handleDeleteTodo = (_id: string): void => { deleteTodo(_id) .then(({ status, data }) => { if (status !== 200) { throw new Error("Error! Todo not deleted") } setTodos(data.todos) }) .catch(err => console.log(err)) } 

The functions to update or delete a Todo are quite similar. They both receive a parameter, send the request, and get back a response. And then, they check if the request has been successful and handle it accordingly.

  • App.tsx
 return (  

My Todos

{todos.map((todo: ITodo) => ( ))} ) } export default App

Here, we loop through the todos array and then pass to the TodoItem the expected data.

Now, if you browse on the folder that contains the server-side app (and execute the following command in the terminal):

yarn start 

And also on the client-side app:

yarn start 

You should see that our Todo app works as expected.

تطبيق

عظيم! بهذه اللمسة الأخيرة ، انتهينا الآن من إنشاء تطبيق Todo باستخدام TypeScript و React و NodeJs و Express و MongoDB.

يمكنك العثور على شفرة المصدر هنا.

يمكنك العثور على محتوى رائع آخر مثل هذا على مدونتي أو متابعتي على Twitter لتلقي إشعارات.

شكرا للقراءة.

مصادر

رد فعل ورقة الغش TypeScript

ورقة غش لأنواع TypeScript المتقدمة (مع أمثلة)

أوراق الغش من TypeScript