ncloud.ts 11 KB

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