ncloud.ts 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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. include(...fileds:string[]) {
  79. this.queryParams["include"] = fileds;
  80. }
  81. greaterThan(key: string, value: any) {
  82. if (!this.queryParams["where"][key]) this.queryParams["where"][key] = {};
  83. this.queryParams["where"][key]["$gt"] = value;
  84. }
  85. greaterThanAndEqualTo(key: string, value: any) {
  86. if (!this.queryParams["where"][key]) this.queryParams["where"][key] = {};
  87. this.queryParams["where"][key]["$gte"] = value;
  88. }
  89. lessThan(key: string, value: any) {
  90. if (!this.queryParams["where"][key]) this.queryParams["where"][key] = {};
  91. this.queryParams["where"][key]["$lt"] = value;
  92. }
  93. lessThanAndEqualTo(key: string, value: any) {
  94. if (!this.queryParams["where"][key]) this.queryParams["where"][key] = {};
  95. this.queryParams["where"][key]["$lte"] = value;
  96. }
  97. equalTo(key: string, value: any) {
  98. this.queryParams["where"][key] = value;
  99. }
  100. async get(id: string) {
  101. const url = `http://dev.fmode.cn:1337/parse/classes/${this.className}/${id}?`;
  102. const response = await fetch(url, {
  103. headers: {
  104. "if-none-match": "W/\"1f0-ghxH2EwTk6Blz0g89ivf2adBDKY\"",
  105. "x-parse-application-id": "dev"
  106. },
  107. body: null,
  108. method: "GET",
  109. mode: "cors",
  110. credentials: "omit"
  111. });
  112. const json = await response?.json();
  113. return json || {};
  114. }
  115. async find() {
  116. let url = `http://dev.fmode.cn:1337/parse/classes/${this.className}?`;
  117. let queryStr = ``
  118. Object.keys(this.queryParams).forEach(key=>{
  119. let paramStr = JSON.stringify(this.queryParams[key]);
  120. if(key=="include"){
  121. paramStr = this.queryParams[key]?.join(",")
  122. }
  123. if(queryStr) {
  124. url += `${key}=${paramStr}`;
  125. }else{
  126. url += `&${key}=${paramStr}`;
  127. }
  128. })
  129. // if (Object.keys(this.queryParams["where"]).length) {
  130. // }
  131. const response = await fetch(url, {
  132. headers: {
  133. "if-none-match": "W/\"1f0-ghxH2EwTk6Blz0g89ivf2adBDKY\"",
  134. "x-parse-application-id": "dev"
  135. },
  136. body: null,
  137. method: "GET",
  138. mode: "cors",
  139. credentials: "omit"
  140. });
  141. const json = await response?.json();
  142. let list = json?.results || []
  143. let objList = list.map((item:any)=>this.dataToObj(item))
  144. return objList || [];
  145. }
  146. async first() {
  147. let url = `http://dev.fmode.cn:1337/parse/classes/${this.className}?`;
  148. if (Object.keys(this.queryParams["where"]).length) {
  149. const whereStr = JSON.stringify(this.queryParams["where"]);
  150. url += `where=${whereStr}`;
  151. }
  152. const response = await fetch(url, {
  153. headers: {
  154. "if-none-match": "W/\"1f0-ghxH2EwTk6Blz0g89ivf2adBDKY\"",
  155. "x-parse-application-id": "dev"
  156. },
  157. body: null,
  158. method: "GET",
  159. mode: "cors",
  160. credentials: "omit"
  161. });
  162. const json = await response?.json();
  163. const exists = json?.results?.[0] || null;
  164. if (exists) {
  165. let existsObject = this.dataToObj(exists)
  166. return existsObject;
  167. }
  168. return null
  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. }