ncloud.ts 11 KB

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