TypeScript实战项目:物联网设备管理系统
随着物联网(IoT)技术的快速发展,越来越多的设备被连接到互联网上,形成了一个庞大的物联网生态系统。在这个生态系统中,设备管理系统的构建变得尤为重要。TypeScript作为一种JavaScript的超集,提供了静态类型检查、接口定义等特性,使得开发大型、复杂的应用程序变得更加容易。本文将围绕TypeScript语言,实战开发一个物联网设备管理系统。
项目背景
物联网设备管理系统主要用于监控、管理、控制和维护物联网设备。该系统需要具备以下功能:
1. 设备注册与认证
2. 设备状态监控
3. 设备数据采集与存储
4. 设备远程控制
5. 设备报警与通知
技术选型
为了实现上述功能,我们选择以下技术栈:
1. TypeScript:用于编写前端和后端代码,提供类型安全。
2. Node.js:作为后端服务器,提供RESTful API接口。
3. Express:Node.js的Web框架,用于构建Web服务器。
4. MongoDB:NoSQL数据库,用于存储设备数据。
5. Socket.IO:用于实现实时通信。
6. React:用于构建前端用户界面。
项目结构
项目结构如下:
IoT-Device-Manager/
├── src/
│ ├── backend/
│ │ ├── index.ts
│ │ ├── device/
│ │ │ ├── index.ts
│ │ │ ├── deviceController.ts
│ │ │ ├── deviceModel.ts
│ │ ├── user/
│ │ │ ├── index.ts
│ │ │ ├── userModel.ts
│ │ ├── auth/
│ │ │ ├── index.ts
│ │ │ ├── authService.ts
│ │ ├── index.ts
│ ├── frontend/
│ │ ├── index.tsx
│ │ ├── components/
│ │ │ ├── DeviceList.tsx
│ │ │ ├── DeviceDetail.tsx
│ │ │ ├── LoginForm.tsx
│ │ ├── App.tsx
│ ├── public/
│ ├── package.json
│ ├── tsconfig.json
│ └── .env
├── test/
│ ├── backend/
│ │ ├── device/
│ │ │ ├── deviceController.test.ts
│ │ ├── user/
│ │ │ ├── userModel.test.ts
│ │ ├── auth/
│ │ │ ├── authService.test.ts
│ ├── frontend/
│ │ ├── components/
│ │ │ ├── DeviceList.test.tsx
│ │ │ ├── DeviceDetail.test.tsx
│ │ │ ├── LoginForm.test.tsx
│ │ ├── App.test.tsx
└── README.md
后端开发
设备管理模块
设备模型(deviceModel.ts)
typescript
import { Document, Schema, model } from 'mongoose';
const deviceSchema = new Schema({
deviceId: { type: String, required: true },
deviceName: { type: String, required: true },
deviceType: { type: String, required: true },
status: { type: String, required: true },
// ...其他设备属性
});
export const Device = model('Device', deviceSchema);
设备控制器(deviceController.ts)
typescript
import { Request, Response } from 'express';
import { Device } from '../models/deviceModel';
export const registerDevice = async (req: Request, res: Response) => {
try {
const { deviceId, deviceName, deviceType, status } = req.body;
const newDevice = new Device({ deviceId, deviceName, deviceType, status });
await newDevice.save();
res.status(201).send(newDevice);
} catch (error) {
res.status(500).send(error);
}
};
export const getDevice = async (req: Request, res: Response) => {
try {
const { deviceId } = req.params;
const device = await Device.findById(deviceId);
if (!device) {
return res.status(404).send('Device not found');
}
res.send(device);
} catch (error) {
res.status(500).send(error);
}
};
用户认证模块
用户模型(userModel.ts)
typescript
import { Document, Schema, model } from 'mongoose';
const userSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
// ...其他用户属性
});
export const User = model('User', userSchema);
认证服务(authService.ts)
typescript
import { Request, Response } from 'express';
import { User } from '../models/userModel';
export const registerUser = async (req: Request, res: Response) => {
try {
const { username, password } = req.body;
const newUser = new User({ username, password });
await newUser.save();
res.status(201).send(newUser);
} catch (error) {
res.status(500).send(error);
}
};
export const loginUser = async (req: Request, res: Response) => {
try {
const { username, password } = req.body;
const user = await User.findOne({ username, password });
if (!user) {
return res.status(401).send('Invalid credentials');
}
res.send(user);
} catch (error) {
res.status(500).send(error);
}
};
前端开发
设备列表组件(DeviceList.tsx)
typescript
import React, { useState, useEffect } from 'react';
import axios from 'axios';
const DeviceList: React.FC = () => {
const [devices, setDevices] = useState([]);
useEffect(() => {
axios.get('/api/devices')
.then(response => {
setDevices(response.data);
})
.catch(error => {
console.error('Error fetching devices:', error);
});
}, []);
return (
{devices.map(device => (
{device.deviceName}
))}
);
};
export default DeviceList;
登录表单组件(LoginForm.tsx)
typescript
import React, { useState } from 'react';
import axios from 'axios';
const LoginForm: React.FC = () => {
const [username, setUsername] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const handleSubmit = async (event: React.FormEvent) => {
event.preventDefault();
try {
const response = await axios.post('/api/auth/login', { username, password });
// Handle login success
} catch (error) {
setError('Invalid credentials');
}
};
return (
Username:
setUsername(e.target.value)}
/>
Comments NOTHING