123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606 |
- /*export interface Pointer {
- __type: string;
- className: string;
- objectId?: string; // 这里保持 objectId 作为可选字段
- //QuestionnaireId?: string; // 自定义主键
- //QuestionId?: string; // 自定义主键
- //OptionId?: string; // 自定义主键
- //_UserId?: string; // 自定义主键
- }
- export class CloudObject {
- id: string | null = null; // 数据库生成的 objectId
- className: string;
- createdAt: string | null = null;
- updatedAt: string | null = null;
- data: Record<string, any> = {};
- // 新增的自定义主键
- QuestionnaireId?: string;
- QuestionId?: string;
- OptionId?: string;
- _UserId?: string;
- constructor(className: string) {
- this.className = className;
- }
- toPointer(): Pointer {
- // 使用自定义主键生成指针
- let pointer: Pointer = { "__type": "Pointer", "className": this.className };
- // 根据类名设置相应的 ID
- switch (this.className) {
- case "Questionnaire":
- pointer.objectId = this.QuestionnaireId || "";
- break;
- case "Question":
- pointer.objectId = this.QuestionId || "";
- break;
- case "Option":
- pointer.objectId = this.OptionId || "";
- break;
- case "_User":
- pointer.objectId = this._UserId || "";
- break;
- default:
- pointer.objectId = this.id || ""; // 保持 objectId 作为后备
- }
- return pointer;
- }
- set(json: Record<string, any>) {
- Object.keys(json).forEach(key => {
- if (["objectId", "id", "createdAt", "updatedAt", "ACL"].includes(key)) {
- return;
- }
- this.data[key] = json[key];
- });
- }
- get(key: string) {
- return this.data[key] || null;
- }
- async save(): Promise<this> {
- let method = "POST";
- let url = `http://dev.fmode.cn:1337/parse/classes/${this.className}`;
- // 更新
- if (this.id) {
- url += `/${this.id}`;
- method = "PUT";
- }
- const body = JSON.stringify(this.data);
- const response = await fetch(url, {
- headers: {
- "content-type": "application/json;charset=UTF-8",
- "x-parse-application-id": "dev"
- },
- 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;
- }
- return this;
- }
- async destroy(): Promise<boolean> {
- if (!this.id) return false;
- const response = await fetch(`http://dev.fmode.cn:1337/parse/classes/${this.className}/${this.id}`, {
- headers: {
- "x-parse-application-id": "dev"
- },
- method: "DELETE",
- mode: "cors",
- credentials: "omit"
- });
- const result = await response.json();
- if (result) {
- this.id = null;
- }
- return true;
- }
- }
- export class CloudQuery {
- className: string;
- whereOptions: Record<string, any> = {};
- constructor(className: string) {
- this.className = className;
- }
- greaterThan(key: string, value: any) {
- if (!this.whereOptions[key]) this.whereOptions[key] = {};
- this.whereOptions[key]["$gt"] = value;
- return this;
- }
- greaterThanAndEqualTo(key: string, value: any) {
- if (!this.whereOptions[key]) this.whereOptions[key] = {};
- this.whereOptions[key]["$gte"] = value;
- return this;
- }
- lessThan(key: string, value: any) {
- if (!this.whereOptions[key]) this.whereOptions[key] = {};
- this.whereOptions[key]["$lt"] = value;
- return this;
- }
- lessThanAndEqualTo(key: string, value: any) {
- if (!this.whereOptions[key]) this.whereOptions[key] = {};
- this.whereOptions[key]["$lte"] = value;
- return this;
- }
- equalTo(key: string, value: any) {
- this.whereOptions[key] = value;
- return this;
- }
- async get(id: string): Promise<Record<string, any>> {
- const url = `http://dev.fmode.cn:1337/parse/classes/${this.className}/${id}`;
- const response = await fetch(url, {
- headers: {
- "x-parse-application-id": "dev"
- },
- method: "GET",
- mode: "cors",
- credentials: "omit"
- });
- const json = await response.json();
- return json || {};
- }
- async find(): Promise<CloudObject[]> {
- let url = `http://dev.fmode.cn:1337/parse/classes/${this.className}?`;
- if (Object.keys(this.whereOptions).length) {
- const whereStr = JSON.stringify(this.whereOptions);
- url += `where=${encodeURIComponent(whereStr)}`;
- }
- const response = await fetch(url, {
- headers: {
- "x-parse-application-id": "dev"
- },
- method: "GET",
- mode: "cors",
- credentials: "omit"
- });
- const json = await response.json();
- return json?.results.map((item: any) => {
- const cloudObject = new CloudObject(this.className);
- cloudObject.set(item);
- cloudObject.id = item.objectId;
- cloudObject.createdAt = item.createdAt;
- cloudObject.updatedAt = item.updatedAt;
- return cloudObject;
- }) || [];
- }
- async first(): Promise<CloudObject | null> {
- let url = `http://dev.fmode.cn:1337/parse/classes/${this.className}?`;
- if (Object.keys(this.whereOptions).length) {
- const whereStr = JSON.stringify(this.whereOptions);
- url += `where=${encodeURIComponent(whereStr)}&limit=1`;
- } else {
- url += `limit=1`;
- }
- const response = await fetch(url, {
- headers: {
- "x-parse-application-id": "dev"
- },
- method: "GET",
- mode: "cors",
- credentials: "omit"
- });
- const json = await response.json();
- const exists = json?.results?.[0] || null;
- if (exists) {
- const cloudObject = new CloudObject(this.className);
- cloudObject.set(exists);
- cloudObject.id = exists.objectId;
- cloudObject.createdAt = exists.createdAt;
- cloudObject.updatedAt = exists.updatedAt;
- return cloudObject;
- }
- return null;
- }
- }*/
- // CloudObject.ts
- export interface Pointer {
- __type: string;
- className: string;
- objectId?: string; // 这里保持 objectId 作为可选字段
- }
- export class CloudObject {
- id: string | null = null;
- className: string;
- data: Record<string, any> = {};
- createdAt: string | null = null;
- updatedAt: string | null = null;
- constructor(className: string) {
- this.className = className;
- }
- toPointer() {
- return { "__type": "Pointer", "className": this.className, "objectId": this.id };
- }
- set(json: Record<string, any>) {
- Object.keys(json).forEach(key => {
- if (["objectId", "id", "createdAt", "updatedAt", "ACL"].includes(key)) {
- if (key === "updatedAt") {
- this.updatedAt = json[key]; // 特别处理 updatedAt 字段
- }
- return;
- }
- this.data[key] = json[key];
- });
- }
- get(key: string) {
- return this.data[key] || null;
- }
- async save(): Promise<CloudObject> {
- let method = "POST";
- let url = `http://dev.fmode.cn:1337/parse/classes/${this.className}`;
- // 更新
- if (this.id) {
- url += `/${this.id}`;
- method = "PUT";
- }
- const body = JSON.stringify(this.data);
- const response = await fetch(url, {
- headers: {
- "Content-Type": "application/json;charset=UTF-8",
- "x-parse-application-id": "dev"
- },
- body,
- method,
- mode: "cors",
- credentials: "omit"
- });
- const result = await response.json();
- if (result?.error) {
- console.error(result.error);
- }
- if (result?.objectId) {
- this.id = result.objectId;
- }
- return this;
- }
- async destroy(): Promise<boolean> {
- if (!this.id) return false;
- const response = await fetch(`http://dev.fmode.cn:1337/parse/classes/${this.className}/${this.id}`, {
- headers: {
- "x-parse-application-id": "dev"
- },
- method: "DELETE",
- mode: "cors",
- credentials: "omit"
- });
- const result = await response?.json();
- if (result) {
- this.id = null;
- }
- return true;
- }
- }
- // CloudQuery.ts
- export class CloudQuery {
- className: string;
- whereOptions: Record<string, any> = {};
- constructor(className: string) {
- this.className = className;
- }
- greaterThan(key: string, value: any) {
- this.whereOptions[key] = { "$gt": value };
- }
- greaterThanAndEqualTo(key: string, value: any) {
- this.whereOptions[key] = { "$gte": value };
- }
- lessThan(key: string, value: any) {
- this.whereOptions[key] = { "$lt": value };
- }
- lessThanAndEqualTo(key: string, value: any) {
- this.whereOptions[key] = { "$lte": value };
- }
- equalTo(key: string, value: any) {
- this.whereOptions[key] = value;
- }
- containedIn(key: string, valueArray: any[]) {
- this.whereOptions[key] = { "$in": valueArray };
- }
- /**
- * 实现 startsWith 方法
- * @param key 要匹配的字段
- * @param prefix 匹配的前缀字符串
- */
- startsWith(key: string, prefix: string) {
- if (typeof prefix !== 'string') {
- throw new Error('The prefix must be a string.');
- }
- // 添加 $regex 条件进行前缀匹配
- this.whereOptions[key] = { "$regex": `^${prefix}` };
- }
- async get(id: string): Promise<Record<string, any>> {
- const url = `http://dev.fmode.cn:1337/parse/classes/${this.className}/${id}?`;
- const response = await fetch(url, {
- headers: {
- "if-none-match": "W/\"1f0-ghxH2EwTk6Blz0g89ivf2adBDKY\"",
- "x-parse-application-id": "dev"
- },
- method: "GET",
- mode: "cors",
- credentials: "omit"
- });
- const json = await response.json();
- return json || {};
- }
- async find(): Promise<CloudObject[]> {
- let url = `http://dev.fmode.cn:1337/parse/classes/${this.className}?`;
- if (Object.keys(this.whereOptions).length) {
- const whereStr = JSON.stringify(this.whereOptions);
- url += `where=${encodeURIComponent(whereStr)}`;
- }
- const response = await fetch(url, {
- headers: {
- "if-none-match": "W/\"1f0-ghxH2EwTk6Blz0g89ivf2BDKY\"",
- "x-parse-application-id": "dev"
- },
- method: "GET",
- mode: "cors",
- credentials: "omit"
- });
- const json = await response.json();
- return json?.results.map((item: any) => {
- const cloudObject = new CloudObject(this.className);
- cloudObject.set(item);
- cloudObject.id = item.objectId;
- // 提取 updatedAt 字段并存储在其他地方(例如,直接存入数据或作为额外字段返回)
- const updatedAt = item.updatedAt; // 提取 updatedAt 字段
- cloudObject.data['updatedAt'] = updatedAt; // 或者将其放在一个独立的变量中,取决于需求
- return cloudObject;
- }) || [];
- }
- async first(): Promise<CloudObject | null> {
- let url = `http://dev.fmode.cn:1337/parse/classes/${this.className}?`;
- if (Object.keys(this.whereOptions).length) {
- const whereStr = JSON.stringify(this.whereOptions);
- url += `where=${encodeURIComponent(whereStr)}`;
- }
- const response = await fetch(url, {
- headers: {
- "if-none-match": "W/\"1f0-ghxH2EwTk6Blz0g89ivf2adBDKY\"",
- "x-parse-application-id": "dev"
- },
- method: "GET",
- mode: "cors",
- credentials: "omit"
- });
- const json = await response.json();
- const exists = json?.results?.[0] || null;
- if (exists) {
- const existsObject = new CloudObject(this.className);
- existsObject.set(exists);
- existsObject.id = exists.objectId;
- existsObject.createdAt = exists.createdAt;
- existsObject.updatedAt = exists.updatedAt;
- return existsObject;
- }
- return null;
- }
- }
- // 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(`http://dev.fmode.cn:1337/parse/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(`http://dev.fmode.cn:1337/parse/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(`http://dev.fmode.cn:1337/parse/logout`, {
- headers: {
- "x-parse-application-id": "dev",
- "x-parse-session-token": this.sessionToken
- },
- method: "POST"
- });
- const result = await response?.json();
- if (result?.error) {
- console.error(result?.error);
- return false;
- }
- // 清除用户信息
- localStorage.removeItem("NCloud/dev/User")
- this.id = null;
- this.sessionToken = null;
- this.data = {};
- return true;
- }
- /** 注册 */
- async signUp(username: string, password: string, additionalData: Record<string, any> = {}) {
- const userData = {
- username,
- password,
- ...additionalData // 合并额外的用户数据
- };
- const response = await fetch(`http://dev.fmode.cn:1337/parse/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 = `http://dev.fmode.cn:1337/parse/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;
- }
- }
|