ncloud.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. import * as Parse from 'parse';
  2. // CloudObject.ts
  3. export class CloudObject {
  4. protected parseObject: Parse.Object;
  5. className: string;
  6. id: string | null = null;
  7. createdAt:any;
  8. updatedAt:any;
  9. data: Record<string, any> = {};
  10. constructor(className: string) {
  11. this.parseObject = new Parse.Object(className);
  12. this.className = className;
  13. }
  14. toPointer() {
  15. return { "__type": "Pointer", "className": this.className, "objectId": this.id };
  16. }
  17. set(json: Record<string, any>) {
  18. Object.keys(json).forEach(key => {
  19. if (["objectId", "id", "createdAt", "updatedAt", "ACL"].indexOf(key) > -1) {
  20. return;
  21. }
  22. this.data[key] = json[key];
  23. });
  24. }
  25. get(key: string) {
  26. return this.data[key] || null;
  27. }
  28. async save() {
  29. let method = "POST";
  30. let url = `http://dev.fmode.cn:1337/parse/classes/${this.className}`;
  31. // 更新
  32. if (this.id) {
  33. url += `/${this.id}`;
  34. method = "PUT";
  35. }
  36. const body = JSON.stringify(this.data);
  37. const response = await fetch(url, {
  38. headers: {
  39. "content-type": "application/json;charset=UTF-8",
  40. "x-parse-application-id": "dev"
  41. },
  42. body: body,
  43. method: method,
  44. mode: "cors",
  45. credentials: "omit"
  46. });
  47. const result = await response?.json();
  48. if (result?.error) {
  49. console.error(result?.error);
  50. }
  51. if (result?.objectId) {
  52. this.id = result?.objectId;
  53. }
  54. return this;
  55. }
  56. async destroy() {
  57. if (!this.id) return;
  58. const response = await fetch(`http://dev.fmode.cn:1337/parse/classes/${this.className}/${this.id}`, {
  59. headers: {
  60. "x-parse-application-id": "dev"
  61. },
  62. body: null,
  63. method: "DELETE",
  64. mode: "cors",
  65. credentials: "omit"
  66. });
  67. const result = await response?.json();
  68. if (result) {
  69. this.id = null;
  70. }
  71. return true;
  72. }
  73. protected setParseObject(obj: Parse.Object) {
  74. this.parseObject = obj;
  75. }
  76. }
  77. // CloudQuery.ts
  78. export class CloudQuery {
  79. private query: Parse.Query;
  80. className: string;
  81. queryParams: Record<string, any> = {};
  82. constructor(className: string) {
  83. this.className = className;
  84. this.query = new Parse.Query(className);
  85. }
  86. // 作用是将查询参数转换为对象
  87. include(...fileds:string[]) {
  88. this.queryParams["include"] = fileds;
  89. }
  90. greaterThan(key: string, value: any) {
  91. if (!this.queryParams["where"][key]) this.queryParams["where"][key] = {};
  92. this.queryParams["where"][key]["$gt"] = value;
  93. }
  94. greaterThanAndEqualTo(key: string, value: any) {
  95. if (!this.queryParams["where"][key]) this.queryParams["where"][key] = {};
  96. this.queryParams["where"][key]["$gte"] = value;
  97. }
  98. lessThan(key: string, value: any) {
  99. if (!this.queryParams["where"][key]) this.queryParams["where"][key] = {};
  100. this.queryParams["where"][key]["$lt"] = value;
  101. }
  102. lessThanAndEqualTo(key: string, value: any) {
  103. if (!this.queryParams["where"][key]) this.queryParams["where"][key] = {};
  104. this.queryParams["where"][key]["$lte"] = value;
  105. }
  106. equalTo(key: string, value: any) {
  107. this.queryParams["where"][key] = value;
  108. }
  109. async get(id: string) {
  110. const url = `http://dev.fmode.cn:1337/parse/classes/${this.className}/${id}?`;
  111. const response = await fetch(url, {
  112. headers: {
  113. "if-none-match": "W/\"1f0-ghxH2EwTk6Blz0g89ivf2adBDKY\"",
  114. "x-parse-application-id": "dev"
  115. },
  116. body: null,
  117. method: "GET",
  118. mode: "cors",
  119. credentials: "omit"
  120. });
  121. const json = await response?.json();
  122. // return json || {};
  123. const exists = json?.results?.[0] || null;
  124. if (exists) {
  125. let existsObject = this.dataToObj(exists)
  126. return existsObject;
  127. }
  128. return null
  129. }
  130. async find(): Promise<CloudObject[]> {
  131. try {
  132. const results = await this.query.find();
  133. return results.map((result: Parse.Object) => {
  134. const obj = new CloudObject(this.className);
  135. (obj as any).parseObject = result; // 使用类型断言
  136. return obj;
  137. });
  138. } catch (error) {
  139. console.error('Query failed:', error);
  140. throw error;
  141. }
  142. }
  143. async first() {
  144. let url = `http://dev.fmode.cn:1337/parse/classes/${this.className}?`;
  145. if (Object.keys(this.queryParams["where"]).length) {
  146. const whereStr = JSON.stringify(this.queryParams["where"]);
  147. url += `where=${whereStr}`;
  148. }
  149. const response = await fetch(url, {
  150. headers: {
  151. "if-none-match": "W/\"1f0-ghxH2EwTk6Blz0g89ivf2adBDKY\"",
  152. "x-parse-application-id": "dev"
  153. },
  154. body: null,
  155. method: "GET",
  156. mode: "cors",
  157. credentials: "omit"
  158. });
  159. const json = await response?.json();
  160. // const exists = json?.results?.[0] || null;
  161. // if (exists) {
  162. // let existsObject = this.dataToObj(exists)
  163. // return existsObject;
  164. // }
  165. // return null
  166. let list = json?.results || []
  167. let objList = list.map((item:any)=>this.dataToObj(item))
  168. return objList || [];
  169. }
  170. dataToObj(exists:any):CloudObject{
  171. let existsObject = new CloudObject(this.className);
  172. existsObject.set(exists);
  173. existsObject.id = exists.objectId;
  174. existsObject.createdAt = exists.createdAt;
  175. existsObject.updatedAt = exists.updatedAt;
  176. return existsObject;
  177. }
  178. }
  179. // CloudUser.ts
  180. export class CloudUser extends CloudObject {
  181. constructor() {
  182. super("_User"); // 假设用户类在Parse中是"_User"
  183. // 读取用户缓存信息
  184. let userCacheStr = localStorage.getItem("NCloud/dev/User")
  185. if(userCacheStr){
  186. let userData = JSON.parse(userCacheStr)
  187. // 设置用户信息
  188. this.id = userData?.objectId;
  189. this.sessionToken = userData?.sessionToken;
  190. this.data = userData; // 保存用户数据
  191. }
  192. }
  193. sessionToken:string|null = ""
  194. /** 获取当前用户信息 */
  195. async current() {
  196. if (!this.sessionToken) {
  197. console.error("用户未登录");
  198. return null;
  199. }
  200. return this;
  201. // const response = await fetch(`http://dev.fmode.cn:1337/parse/users/me`, {
  202. // headers: {
  203. // "x-parse-application-id": "dev",
  204. // "x-parse-session-token": this.sessionToken // 使用sessionToken进行身份验证
  205. // },
  206. // method: "GET"
  207. // });
  208. // const result = await response?.json();
  209. // if (result?.error) {
  210. // console.error(result?.error);
  211. // return null;
  212. // }
  213. // return result;
  214. }
  215. /** 登录 */
  216. async login(username: string, password: string):Promise<CloudUser|null> {
  217. const response = await fetch(`http://dev.fmode.cn:1337/parse/login`, {
  218. headers: {
  219. "x-parse-application-id": "dev",
  220. "Content-Type": "application/json"
  221. },
  222. body: JSON.stringify({ username, password }),
  223. method: "POST"
  224. });
  225. const result = await response?.json();
  226. if (result?.error) {
  227. console.error(result?.error);
  228. return null;
  229. }
  230. // 设置用户信息
  231. this.id = result?.objectId;
  232. this.sessionToken = result?.sessionToken;
  233. this.data = result; // 保存用户数据
  234. // 缓存用户信息
  235. console.log(result)
  236. localStorage.setItem("NCloud/dev/User",JSON.stringify(result))
  237. return this;
  238. }
  239. /** 登出 */
  240. async logout() {
  241. if (!this.sessionToken) {
  242. console.error("用户未登录");
  243. return;
  244. }
  245. const response = await fetch(`http://dev.fmode.cn:1337/parse/logout`, {
  246. headers: {
  247. "x-parse-application-id": "dev",
  248. "x-parse-session-token": this.sessionToken
  249. },
  250. method: "POST"
  251. });
  252. const result = await response?.json();
  253. if (result?.error) {
  254. console.error(result?.error);
  255. return false;
  256. }
  257. // 清除用户信息
  258. localStorage.removeItem("NCloud/dev/User")
  259. this.id = null;
  260. this.sessionToken = null;
  261. this.data = {};
  262. return true;
  263. }
  264. /** 注册 */
  265. async signUp(username: string, password: string, additionalData: Record<string, any> = {}) {
  266. const userData = {
  267. username,
  268. password,
  269. ...additionalData // 合并额外的用户��据
  270. };
  271. const response = await fetch(`http://dev.fmode.cn:1337/parse/users`, {
  272. headers: {
  273. "x-parse-application-id": "dev",
  274. "Content-Type": "application/json"
  275. },
  276. body: JSON.stringify(userData),
  277. method: "POST"
  278. });
  279. const result = await response?.json();
  280. if (result?.error) {
  281. console.error(result?.error);
  282. return null;
  283. }
  284. // 设置用户信息
  285. // 缓存用户信息
  286. console.log(result)
  287. localStorage.setItem("NCloud/dev/User",JSON.stringify(result))
  288. this.id = result?.objectId;
  289. this.sessionToken = result?.sessionToken;
  290. this.data = result; // 保存用户数据
  291. return this;
  292. }
  293. override async save() {
  294. let method = "POST";
  295. let url = `http://dev.fmode.cn:1337/parse/users`;
  296. // 更新用户信息
  297. if (this.id) {
  298. url += `/${this.id}`;
  299. method = "PUT";
  300. }
  301. let data:any = JSON.parse(JSON.stringify(this.data))
  302. delete data.createdAt
  303. delete data.updatedAt
  304. delete data.ACL
  305. delete data.objectId
  306. const body = JSON.stringify(data);
  307. let headersOptions:any = {
  308. "content-type": "application/json;charset=UTF-8",
  309. "x-parse-application-id": "dev",
  310. "x-parse-session-token": this.sessionToken, // 添加sessionToken以进行身份验证
  311. }
  312. const response = await fetch(url, {
  313. headers: headersOptions,
  314. body: body,
  315. method: method,
  316. mode: "cors",
  317. credentials: "omit"
  318. });
  319. const result = await response?.json();
  320. if (result?.error) {
  321. console.error(result?.error);
  322. }
  323. if (result?.objectId) {
  324. this.id = result?.objectId;
  325. }
  326. localStorage.setItem("NCloud/dev/User",JSON.stringify(this.data))
  327. return this;
  328. }
  329. }