update APItest Demo

This commit is contained in:
Lin Weiting 2025-02-10 18:49:34 +08:00
parent 258c3cb667
commit 70ff15bee7
22 changed files with 3754 additions and 47 deletions

View File

@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?

View File

@ -0,0 +1,3 @@
### api測試
一個table表對應一個ts檔定義api呼叫方式在一個class將這些ts檔放在api資料夾內
index.ts將這些class整理起來並實例化export給前端tsx用

View File

@ -0,0 +1,28 @@
import js from '@eslint/js'
import globals from 'globals'
import reactHooks from 'eslint-plugin-react-hooks'
import reactRefresh from 'eslint-plugin-react-refresh'
import tseslint from 'typescript-eslint'
export default tseslint.config(
{ ignores: ['dist'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
plugins: {
'react-hooks': reactHooks,
'react-refresh': reactRefresh,
},
rules: {
...reactHooks.configs.recommended.rules,
'react-refresh/only-export-components': [
'warn',
{ allowConstantExport: true },
],
},
},
)

View File

@ -0,0 +1,13 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + React + TS</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,30 @@
{
"name": "api_demo",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
},
"dependencies": {
"axios": "^1.7.9",
"react": "^19.0.0",
"react-dom": "^19.0.0"
},
"devDependencies": {
"@eslint/js": "^9.19.0",
"@types/react": "^19.0.8",
"@types/react-dom": "^19.0.3",
"@vitejs/plugin-react": "^4.3.4",
"eslint": "^9.19.0",
"eslint-plugin-react-hooks": "^5.0.0",
"eslint-plugin-react-refresh": "^0.4.18",
"globals": "^15.14.0",
"typescript": "~5.7.2",
"typescript-eslint": "^8.22.0",
"vite": "^6.1.0"
}
}

View File

@ -0,0 +1,87 @@
import React, { useEffect, useState } from "react";
import * as api from "./api/index"
const HomePage: React.FC = () => {
const [data,setdata] = useState<api.apiResponse[]>([])
const [selectmode,setselectmode] = useState<string>("")
const [loading,setloading] = useState<boolean>(false)
useEffect(() => {
const fetchData = async () => {
setloading(true); // 開始載入
try {
let apiInstance;
switch (selectmode) {
case "Model_camera":
apiInstance = api.api_camera;
break;
case "Model_em":
apiInstance = api.api_em;
break;
case "Model_line":
apiInstance = api.api_line;
break;
case "Model_rose":
apiInstance = api.api_rose;
break;
default:
apiInstance = api.api_camera; // 預設值
}
const data = await apiInstance.GetData(); // 執行 API 請求
setdata(data);
} catch (error) {
console.error("API 請求錯誤:", error);
} finally {
setloading(false); // 無論成功或失敗,關閉 loading
}
};
fetchData();
}, [selectmode]); // 監聽 selectmode 變更
return (
<div >
<h1></h1>
<select value={selectmode} onChange={(e)=>{setselectmode(e.target.value)}}>
<option value="Model_camera"></option>
<option value="Model_em"></option>
<option value="Model_line"></option>
<option value="Model_rose"></option>
</select>
<h2></h2>
{loading ? "-------載入中-------":(
<ul>
{data.map((item) => (
<li key={item.item}>
<strong></strong> {item.item} <br />
<strong></strong> {item.account} <br />
<strong></strong> {item.location} <br />
{/* <strong>圖片:</strong> {item.itemimage} */}
<img src={`data:image/jpeg;base64,${item.itemimage}`} alt="Base64圖片" />
</li>
))}
</ul>
)}
</div>
);
};
export default HomePage;

View File

@ -0,0 +1,21 @@
import axios from "axios";
import { ApiResponse } from "./api_types";
export class Api_camera {
private API_URL:string ;
private modelName = "Model_camera";
constructor(ipAddress: string) {
this.API_URL = ipAddress;
}
async GetData(): Promise<ApiResponse[]> {
try {
const response = await axios.get<ApiResponse[]>(`${this.API_URL}/${this.modelName}`);
return response.data;
} catch (error) {
console.error("API????", error);
throw error;
}
}
}

View File

@ -0,0 +1,21 @@
import axios from "axios";
import { ApiResponse } from "./api_types";
export class Api_em {
private API_URL:string ;
private modelName = "Model_em";
constructor(ipAddress: string) {
this.API_URL = ipAddress;
}
async GetData(): Promise<ApiResponse[]> {
try {
const response = await axios.get<ApiResponse[]>(`${this.API_URL}/${this.modelName}`);
return response.data;
} catch (error) {
console.error("API????", error);
throw error;
}
}
}

View File

@ -0,0 +1,21 @@
import axios from "axios";
import { ApiResponse } from "./api_types";
export class Api_line {
private API_URL:string ;
private modelName = "Model_line";
constructor(ipAddress: string) {
this.API_URL = ipAddress;
}
async GetData(): Promise<ApiResponse[]> {
try {
const response = await axios.get<ApiResponse[]>(`${this.API_URL}/${this.modelName}`);
return response.data;
} catch (error) {
console.error("API ????", error);
throw error;
}
}
}

View File

@ -0,0 +1,21 @@
import axios from "axios";
import { ApiResponse } from "./api_types";
export class Api_rent {
private API_URL:string ;
private modelName = "Model_rent";
constructor(ipAddress: string) {
this.API_URL = ipAddress;
}
async GetData(): Promise<ApiResponse[]> {
try {
const response = await axios.get<ApiResponse[]>(`${this.API_URL}/${this.modelName}`);
return response.data;
} catch (error) {
console.error("API 請求錯誤:", error);
throw error;
}
}
}

View File

@ -0,0 +1,21 @@
import axios from "axios";
import { ApiResponse } from "./api_types";
export class Api_rose {
private API_URL:string ;
private modelName = "Model_rose";
constructor(ipAddress: string) {
this.API_URL = ipAddress;
}
async GetData(): Promise<ApiResponse[]> {
try {
const response = await axios.get<ApiResponse[]>(`${this.API_URL}/${this.modelName}`);
return response.data;
} catch (error) {
console.error("API ????", error);
throw error;
}
}
}

View File

@ -0,0 +1,6 @@
export interface ApiResponse {
item: string;
account: string;
location: string;
itemimage: string;
}

View File

@ -0,0 +1,21 @@
import axios from "axios";
import { ApiResponse } from "./api_types";
export class Api_user {
private API_URL:string ;
private modelName = "Model_user";
constructor(ipAddress: string) {
this.API_URL = ipAddress;
}
async GetData(): Promise<ApiResponse[]> {
try {
const response = await axios.get<ApiResponse[]>(`${this.API_URL}/${this.modelName}`);
return response.data;
} catch (error) {
console.error("API ½Ð¨D¿ù»~¡G", error);
throw error;
}
}
}

View File

@ -0,0 +1,14 @@
import { Api_em } from "./api_em";
import { Api_line } from "./api_line";
import { Api_rose } from "./api_rose";
import { Api_camera } from "./api_camera";
import { ApiResponse} from "./api_types";
// ? ³]©w IP
const IP_ADDRESS = "http://140.125.21.70:7071/api";
// ? ¤â°Ê«Ø¥ß API ¹ê¨Ò
export type apiResponse = ApiResponse;
export const api_em = new Api_em(IP_ADDRESS);
export const api_line = new Api_line(IP_ADDRESS);
export const api_rose = new Api_rose(IP_ADDRESS);
export const api_camera = new Api_camera(IP_ADDRESS);

View File

@ -0,0 +1,9 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import HomePage from './App.tsx'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<HomePage />
</StrictMode>,
)

View File

@ -0,0 +1 @@
/// <reference types="vite/client" />

View File

@ -0,0 +1,26 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src"]
}

View File

@ -0,0 +1,7 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}

View File

@ -0,0 +1,24 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["vite.config.ts"]
}

View File

@ -0,0 +1,13 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
// https://vite.dev/config/
export default defineConfig({
plugins: [react()],
server: {
host: 'localhost', // 指定 IP
port: 3001, // 可更改為不同的 Port
strictPort: true, // 如果 Port 被占用則報錯
open: true, // 啟動時自動打開瀏覽器
}
})

View File

@ -1,50 +1,20 @@
# React + TypeScript + Vite ### 文件導航測試
- [(必要)了解基本知識](docs/Basic.md)
- [(必要)認識專案結構](docs/Structure.md)
This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. # 創建一個React專案
於準備開發的資料夾下方開啟CMD並執行
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react/README.md) uses [Babel](https://babeljs.io/) for Fast Refresh
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react-swc) uses [SWC](https://swc.rs/) for Fast Refresh
## Expanding the ESLint configuration
If you are developing a production application, we recommend updating the configuration to enable type aware lint rules:
- Configure the top-level `parserOptions` property like this:
```js
export default tseslint.config({
languageOptions: {
// other options...
parserOptions: {
project: ['./tsconfig.node.json', './tsconfig.app.json'],
tsconfigRootDir: import.meta.dirname,
},
},
})
``` ```
npm create vite@latest my-project --template react-ts
- Replace `tseslint.configs.recommended` to `tseslint.configs.recommendedTypeChecked` or `tseslint.configs.strictTypeChecked` cd my-project
- Optionally add `...tseslint.configs.stylisticTypeChecked` npm install
- Install [eslint-plugin-react](https://github.com/jsx-eslint/eslint-plugin-react) and update the config: npm run dev
```
```js ![image](assets/startReact.png)
// eslint.config.js
import react from 'eslint-plugin-react' #執行demo專案
開vscode到該專案資料夾(例如todolist_demo)
export default tseslint.config({ 開啟終端機
// Set the react version ```
settings: { react: { version: '18.3' } }, npm run dev
plugins: {
// Add the react plugin
react,
},
rules: {
// other rules...
// Enable its recommended rules
...react.configs.recommended.rules,
...react.configs['jsx-runtime'].rules,
},
})
``` ```