Browse Source

feat:management

匡智超 2 days ago
parent
commit
d5bdfb4484

+ 35 - 0
cloth-design/src/app/modules/cloth/mobile/device-management/device-management.html

@@ -0,0 +1,35 @@
+<!-- device-management.component.html -->
+<div class="container">
+  <h2>设备管理</h2>
+
+  <div class="new-device">
+    <input type="text" [(ngModel)]="newDeviceName" placeholder="设备名称" />
+    <button (click)="addDevice()">添加设备</button>
+  </div>
+
+  @if(devices.length > 0; else noDevices) {
+    <div class="devices-list">
+      @for(device of devices; track device.id) {
+        <div class="device" (click)="selectDevice(device)">
+          <span>{{ device.get('name') }}</span>
+          <button (click)="deleteDevice(device)">删除</button>
+        </div>
+      }
+    </div>
+  }
+
+  <ng-template #noDevices>
+    <p>没有设备。</p>
+  </ng-template>
+
+  @if(selectedDevice; else noSelectedDevice) {
+    <div class="selected-device">
+      <h3>选中的设备</h3>
+      <p>{{ selectedDevice.get('name') }}</p>
+    </div>
+  }
+
+  <ng-template #noSelectedDevice>
+    <p>没有选中的设备。</p>
+  </ng-template>
+</div>

+ 29 - 0
cloth-design/src/app/modules/cloth/mobile/device-management/device-management.scss

@@ -0,0 +1,29 @@
+/* device-management.component.scss */
+.container {
+  max-width: 800px;
+  margin: 0 auto;
+  padding: 20px;
+}
+
+.new-device {
+  display: flex;
+  gap: 10px;
+  margin-bottom: 20px;
+}
+
+.devices-list {
+  margin-bottom: 20px;
+}
+
+.device {
+  display: flex;
+  justify-content: space-between;
+  align-items: center;
+  padding: 10px;
+  border: 1px solid #ccc;
+  margin-bottom: 10px;
+  cursor: pointer;
+}
+.device:hover {
+  background-color: #f0f0f0;
+}

+ 23 - 0
cloth-design/src/app/modules/cloth/mobile/device-management/device-management.spec.ts

@@ -0,0 +1,23 @@
+import { ComponentFixture, TestBed } from '@angular/core/testing';
+
+import { DeviceManagement } from './device-management';
+
+describe('DeviceManagement', () => {
+  let component: DeviceManagement;
+  let fixture: ComponentFixture<DeviceManagement>;
+
+  beforeEach(async () => {
+    await TestBed.configureTestingModule({
+      imports: [DeviceManagement]
+    })
+    .compileComponents();
+
+    fixture = TestBed.createComponent(DeviceManagement);
+    component = fixture.componentInstance;
+    fixture.detectChanges();
+  });
+
+  it('should create', () => {
+    expect(component).toBeTruthy();
+  });
+});

+ 51 - 0
cloth-design/src/app/modules/cloth/mobile/device-management/device-management.ts

@@ -0,0 +1,51 @@
+// device-management.component.ts
+import { Component, OnInit } from '@angular/core';
+import { CloudObject } from './cloud-object';
+import { CloudQuery } from './../lib/ncloud.ts';
+
+@Component({
+  selector: 'app-device-management',
+  standalone: true,
+  imports: [
+    // 确保导入了必要的模块
+  ],
+  templateUrl: './device-management.component.html',
+  styleUrls: ['./device-management.component.scss']
+})
+export class DeviceManagementComponent implements OnInit {
+  devices: CloudObject[] = [];
+  newDeviceName: string = '';
+  selectedDevice: CloudObject | undefined;
+
+  private deviceQuery: CloudQuery;
+
+  constructor() {
+    this.deviceQuery = new CloudQuery("Device");
+  }
+
+  async ngOnInit() {
+    await this.loadDevices();
+  }
+
+  async loadDevices() {
+    const devices = await this.deviceQuery.find();
+    this.devices = devices;
+  }
+
+  async addDevice() {
+    const device = new CloudObject("Device");
+    device.set({ name: this.newDeviceName });
+    await device.save();
+    this.devices.push(device);
+    this.newDeviceName = '';
+  }
+
+  async deleteDevice(device: CloudObject) {
+    await device.destroy();
+    this.devices = this.devices.filter(d => d.id !== device.id);
+  }
+
+  selectDevice(device: CloudObject) {
+    this.selectedDevice = device;
+  }
+}

+ 44 - 280
cloth-design/src/lib/ncloud.ts

@@ -1,5 +1,6 @@
 // CloudObject.ts
 
+// cloud-object.ts
 let serverURL = `https://dev.fmode.cn/parse`;
 if (location.protocol == "http:") {
     serverURL = `http://dev.fmode.cn:1337/parse`;
@@ -22,7 +23,7 @@ export class CloudObject {
 
     set(json: Record<string, any>) {
         Object.keys(json).forEach(key => {
-            if (["objectId", "id", "createdAt", "updatedAt"].indexOf(key) > -1) {
+            if (["objectId", "id", "createdAt", "updatedAt"].includes(key)) {
                 return;
             }
             this.data[key] = json[key];
@@ -35,7 +36,7 @@ export class CloudObject {
 
     async save() {
         let method = "POST";
-        let url = serverURL + `/classes/${this.className}`;
+        let url = `${serverURL}/classes/${this.className}`;
 
         // 更新
         if (this.id) {
@@ -46,8 +47,8 @@ export class CloudObject {
         const body = JSON.stringify(this.data);
         const response = await fetch(url, {
             headers: {
-                "content-type": "application/json;charset=UTF-8",
-                "x-parse-application-id": "dev"
+                "Content-Type": "application/json;charset=UTF-8",
+                "X-Parse-Application-Id": "dev"
             },
             body: body,
             method: method,
@@ -55,37 +56,41 @@ export class CloudObject {
             credentials: "omit"
         });
 
-        const result = await response?.json();
-        if (result?.error) {
-            console.error(result?.error);
+        const result = await response.json();
+        if (result.error) {
+            console.error(result.error);
         }
-        if (result?.objectId) {
-            this.id = result?.objectId;
+        if (result.objectId) {
+            this.id = result.objectId;
+            this.createdAt = result.createdAt;
+            this.updatedAt = result.updatedAt;
         }
         return this;
     }
 
     async destroy() {
         if (!this.id) return;
-        const response = await fetch(serverURL + `/classes/${this.className}/${this.id}`, {
+        const response = await fetch(`${serverURL}/classes/${this.className}/${this.id}`, {
             headers: {
-                "x-parse-application-id": "dev"
+                "X-Parse-Application-Id": "dev"
             },
-            body: null,
             method: "DELETE",
             mode: "cors",
             credentials: "omit"
         });
 
-        const result = await response?.json();
+        const result = await response.json();
         if (result) {
             this.id = undefined;
+            this.createdAt = undefined;
+            this.updatedAt = undefined;
+            this.data = {};
         }
         return true;
     }
 }
-
 // CloudQuery.ts
+// cloud-query.ts
 export class CloudQuery {
     className: string;
     queryParams: Record<string, any> = { where: {} };
@@ -94,9 +99,10 @@ export class CloudQuery {
         this.className = className;
     }
 
-    include(...fileds: string[]) {
-        this.queryParams["include"] = fileds;
+    include(...fields: string[]) {
+        this.queryParams["include"] = fields.join(",");
     }
+
     greaterThan(key: string, value: any) {
         if (!this.queryParams["where"][key]) this.queryParams["where"][key] = {};
         this.queryParams["where"][key]["$gt"] = value;
@@ -118,314 +124,72 @@ export class CloudQuery {
     }
 
     equalTo(key: string, value: any) {
-        if (!this.queryParams["where"]) this.queryParams["where"] = {};
         this.queryParams["where"][key] = value;
     }
 
     async get(id: string) {
-        const url = serverURL + `/classes/${this.className}/${id}?`;
+        const url = `${serverURL}/classes/${this.className}/${id}`;
 
         const response = await fetch(url, {
             headers: {
-                "if-none-match": "W/\"1f0-ghxH2EwTk6Blz0g89ivf2adBDKY\"",
-                "x-parse-application-id": "dev"
+                "X-Parse-Application-Id": "dev"
             },
-            body: null,
             method: "GET",
             mode: "cors",
             credentials: "omit"
         });
 
-        const json = await response?.json();
-        if (json) {
-            let existsObject = this.dataToObj(json)
-            return existsObject;
+        const json = await response.json();
+        if (json.error) {
+            console.error(json.error);
+            return null;
         }
-        return null
+        return this.dataToObj(json);
     }
 
     async find(): Promise<Array<CloudObject>> {
-        let url = serverURL + `/classes/${this.className}?`;
+        let url = `${serverURL}/classes/${this.className}?`;
 
-        let queryStr = ``
+        let queryStr = "";
         Object.keys(this.queryParams).forEach(key => {
             let paramStr = JSON.stringify(this.queryParams[key]);
-            if (key == "include") {
-                paramStr = this.queryParams[key]?.join(",")
+            if (key === "include") {
+                paramStr = this.queryParams[key];
             }
             if (queryStr) {
-                url += `${key}=${paramStr}`;
+                url += `&${key}=${encodeURIComponent(paramStr)}`;
             } else {
-                url += `&${key}=${paramStr}`;
+                url += `${key}=${encodeURIComponent(paramStr)}`;
             }
-        })
-        // if (Object.keys(this.queryParams["where"]).length) {
-
-        // }
-
-        const response = await fetch(url, {
-            headers: {
-                "if-none-match": "W/\"1f0-ghxH2EwTk6Blz0g89ivf2adBDKY\"",
-                "x-parse-application-id": "dev"
-            },
-            body: null,
-            method: "GET",
-            mode: "cors",
-            credentials: "omit"
         });
 
-        const json = await response?.json();
-        let list = json?.results || []
-        let objList = list.map((item: any) => this.dataToObj(item))
-        return objList || [];
-    }
-
-
-    async first() {
-        let url = serverURL + `/classes/${this.className}?`;
-
-        if (Object.keys(this.queryParams["where"]).length) {
-            const whereStr = JSON.stringify(this.queryParams["where"]);
-            url += `where=${whereStr}&limit=1`;
-        }
-
         const response = await fetch(url, {
             headers: {
-                "if-none-match": "W/\"1f0-ghxH2EwTk6Blz0g89ivf2adBDKY\"",
-                "x-parse-application-id": "dev"
+                "X-Parse-Application-Id": "dev"
             },
-            body: null,
             method: "GET",
             mode: "cors",
             credentials: "omit"
         });
 
-        const json = await response?.json();
-        const exists = json?.results?.[0] || null;
-        if (exists) {
-            let existsObject = this.dataToObj(exists)
-            return existsObject;
-        }
-        return null
+        const json = await response.json();
+        let list = json.results || [];
+        let objList = list.map((item: any) => this.dataToObj(item));
+        return objList;
     }
 
     dataToObj(exists: any): CloudObject {
         let existsObject = new CloudObject(this.className);
         Object.keys(exists).forEach(key => {
-            if (exists[key]?.__type == "Object") {
-                exists[key] = this.dataToObj(exists[key])
+            if (exists[key]?.__type === "Pointer") {
+                exists[key] = new CloudObject(exists[key].className);
+                exists[key].id = exists[key].objectId;
             }
-        })
+        });
         existsObject.set(exists);
         existsObject.id = exists.objectId;
         existsObject.createdAt = exists.createdAt;
         existsObject.updatedAt = exists.updatedAt;
         return existsObject;
     }
-}
-
-// CloudUser.ts
-export class CloudUser extends CloudObject {
-    constructor() {
-        super("_User"); // 假设用户类在Parse中是"_User"
-        // 读取用户缓存信息
-        let userCacheStr = localStorage.getItem("NCloud/dev/User")
-        if (userCacheStr) {
-            let userData = JSON.parse(userCacheStr)
-            // 设置用户信息
-            this.id = userData?.objectId;
-            this.sessionToken = userData?.sessionToken;
-            this.data = userData; // 保存用户数据
-        }
-    }
-
-    sessionToken: string | null = ""
-    /** 获取当前用户信息 */
-    async current() {
-        if (!this.sessionToken) {
-            console.error("用户未登录");
-            return null;
-        }
-        return this;
-        // const response = await fetch(serverURL + `/users/me`, {
-        //     headers: {
-        //         "x-parse-application-id": "dev",
-        //         "x-parse-session-token": this.sessionToken // 使用sessionToken进行身份验证
-        //     },
-        //     method: "GET"
-        // });
-
-        // const result = await response?.json();
-        // if (result?.error) {
-        //     console.error(result?.error);
-        //     return null;
-        // }
-        // return result;
-    }
-
-    /** 登录 */
-    async login(username: string, password: string): Promise<CloudUser | null> {
-        const response = await fetch(serverURL + `/login`, {
-            headers: {
-                "x-parse-application-id": "dev",
-                "Content-Type": "application/json"
-            },
-            body: JSON.stringify({ username, password }),
-            method: "POST"
-        });
-
-        const result = await response?.json();
-        if (result?.error) {
-            console.error(result?.error);
-            return null;
-        }
-
-        // 设置用户信息
-        this.id = result?.objectId;
-        this.sessionToken = result?.sessionToken;
-        this.data = result; // 保存用户数据
-        // 缓存用户信息
-        console.log(result)
-        localStorage.setItem("NCloud/dev/User", JSON.stringify(result))
-        return this;
-    }
-
-    /** 登出 */
-    async logout() {
-        if (!this.sessionToken) {
-            console.error("用户未登录");
-            return;
-        }
-
-        const response = await fetch(serverURL + `/logout`, {
-            headers: {
-                "x-parse-application-id": "dev",
-                "x-parse-session-token": this.sessionToken
-            },
-            method: "POST"
-        });
-
-        let result = await response?.json();
-
-        if (result?.error) {
-            console.error(result?.error);
-            if (result?.error == "Invalid session token") {
-                this.clearUserCache()
-                return true;
-            }
-            return false;
-        }
-
-        this.clearUserCache()
-        return true;
-    }
-    clearUserCache() {
-        // 清除用户信息
-        localStorage.removeItem("NCloud/dev/User")
-        this.id = undefined;
-        this.sessionToken = null;
-        this.data = {};
-    }
-
-    /** 注册 */
-    async signUp(username: string, password: string, additionalData: Record<string, any> = {}) {
-        const userData = {
-            username,
-            password,
-            ...additionalData // 合并额外的用户数据
-        };
-
-        const response = await fetch(serverURL + `/users`, {
-            headers: {
-                "x-parse-application-id": "dev",
-                "Content-Type": "application/json"
-            },
-            body: JSON.stringify(userData),
-            method: "POST"
-        });
-
-        const result = await response?.json();
-        if (result?.error) {
-            console.error(result?.error);
-            return null;
-        }
-
-        // 设置用户信息
-        // 缓存用户信息
-        console.log(result)
-        localStorage.setItem("NCloud/dev/User", JSON.stringify(result))
-        this.id = result?.objectId;
-        this.sessionToken = result?.sessionToken;
-        this.data = result; // 保存用户数据
-        return this;
-    }
-
-    override async save() {
-        let method = "POST";
-        let url = serverURL + `/users`;
-
-        // 更新用户信息
-        if (this.id) {
-            url += `/${this.id}`;
-            method = "PUT";
-        }
-
-        let data: any = JSON.parse(JSON.stringify(this.data))
-        delete data.createdAt
-        delete data.updatedAt
-        delete data.ACL
-        delete data.objectId
-        const body = JSON.stringify(data);
-        let headersOptions: any = {
-            "content-type": "application/json;charset=UTF-8",
-            "x-parse-application-id": "dev",
-            "x-parse-session-token": this.sessionToken, // 添加sessionToken以进行身份验证
-        }
-        const response = await fetch(url, {
-            headers: headersOptions,
-            body: body,
-            method: method,
-            mode: "cors",
-            credentials: "omit"
-        });
-
-        const result = await response?.json();
-        if (result?.error) {
-            console.error(result?.error);
-        }
-        if (result?.objectId) {
-            this.id = result?.objectId;
-        }
-        localStorage.setItem("NCloud/dev/User", JSON.stringify(this.data))
-        return this;
-    }
-}
-
-export class CloudApi {
-    async fetch(path: string, body: any, options?: {
-        method: string
-        body: any
-    }) {
-
-        let reqOpts: any = {
-            headers: {
-                "x-parse-application-id": "dev",
-                "Content-Type": "application/json"
-            },
-            method: options?.method || "POST",
-            mode: "cors",
-            credentials: "omit"
-        }
-        if (body || options?.body) {
-            reqOpts.body = JSON.stringify(body || options?.body);
-            reqOpts.json = true;
-        }
-        let host = `https://dev.fmode.cn`
-        // host = `http://127.0.0.1:1337`
-        let url = `${host}/api/` + path
-        console.log(url, reqOpts)
-        const response = await fetch(url, reqOpts);
-        let json = await response.json();
-        return json
-    }
 }