ncloud.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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 = `https://dev.fmode.cn/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(`https://dev.fmode.cn/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. if (!this.queryParams["where"]) this.queryParams["where"] = {};
  99. this.queryParams["where"][key] = value;
  100. }
  101. async get(id: string) {
  102. const url = `https://dev.fmode.cn/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. if (json) {
  115. let existsObject = this.dataToObj(json)
  116. return existsObject;
  117. }
  118. return null
  119. }
  120. async find():Promise<Array<CloudObject>> {
  121. let url = `https://dev.fmode.cn/parse/classes/${this.className}?`;
  122. let queryStr = ``
  123. Object.keys(this.queryParams).forEach(key=>{
  124. let paramStr = JSON.stringify(this.queryParams[key]);
  125. if(key=="include"){
  126. paramStr = this.queryParams[key]?.join(",")
  127. }
  128. if(queryStr) {
  129. url += `${key}=${paramStr}`;
  130. }else{
  131. url += `&${key}=${paramStr}`;
  132. }
  133. })
  134. // if (Object.keys(this.queryParams["where"]).length) {
  135. // }
  136. const response = await fetch(url, {
  137. headers: {
  138. "if-none-match": "W/\"1f0-ghxH2EwTk6Blz0g89ivf2adBDKY\"",
  139. "x-parse-application-id": "dev"
  140. },
  141. body: null,
  142. method: "GET",
  143. mode: "cors",
  144. credentials: "omit"
  145. });
  146. const json = await response?.json();
  147. let list = json?.results || []
  148. let objList = list.map((item:any)=>this.dataToObj(item))
  149. return objList || [];
  150. }
  151. async first() {
  152. let url = `https://dev.fmode.cn/parse/classes/${this.className}?`;
  153. if (Object.keys(this.queryParams["where"]).length) {
  154. const whereStr = JSON.stringify(this.queryParams["where"]);
  155. url += `where=${whereStr}`;
  156. }
  157. const response = await fetch(url, {
  158. headers: {
  159. "if-none-match": "W/\"1f0-ghxH2EwTk6Blz0g89ivf2adBDKY\"",
  160. "x-parse-application-id": "dev"
  161. },
  162. body: null,
  163. method: "GET",
  164. mode: "cors",
  165. credentials: "omit"
  166. });
  167. const json = await response?.json();
  168. const exists = json?.results?.[0] || null;
  169. if (exists) {
  170. let existsObject = this.dataToObj(exists)
  171. return existsObject;
  172. }
  173. return null
  174. }
  175. dataToObj(exists:any):CloudObject{
  176. let existsObject = new CloudObject(this.className);
  177. existsObject.set(exists);
  178. existsObject.id = exists.objectId;
  179. existsObject.createdAt = exists.createdAt;
  180. existsObject.updatedAt = exists.updatedAt;
  181. return existsObject;
  182. }
  183. }
  184. // CloudUser.ts
  185. export class CloudUser extends CloudObject {
  186. constructor() {
  187. super("_User"); // 假设用户类在Parse中是"_User"
  188. // 读取用户缓存信息
  189. let userCacheStr = localStorage.getItem("NCloud/dev/User")
  190. if(userCacheStr){
  191. let userData = JSON.parse(userCacheStr)
  192. // 设置用户信息
  193. this.id = userData?.objectId;
  194. this.sessionToken = userData?.sessionToken;
  195. this.data = userData; // 保存用户数据
  196. }
  197. }
  198. sessionToken:string|null = ""
  199. /** 获取当前用户信息 */
  200. async current() {
  201. if (!this.sessionToken) {
  202. console.error("用户未登录");
  203. return null;
  204. }
  205. return this;
  206. // const response = await fetch(`https://dev.fmode.cn/parse/users/me`, {
  207. // headers: {
  208. // "x-parse-application-id": "dev",
  209. // "x-parse-session-token": this.sessionToken // 使用sessionToken进行身份验证
  210. // },
  211. // method: "GET"
  212. // });
  213. // const result = await response?.json();
  214. // if (result?.error) {
  215. // console.error(result?.error);
  216. // return null;
  217. // }
  218. // return result;
  219. }
  220. /** 登录 */
  221. async login(username: string, password: string):Promise<CloudUser|null> {
  222. const response = await fetch(`https://dev.fmode.cn/parse/login`, {
  223. headers: {
  224. "x-parse-application-id": "dev",
  225. "Content-Type": "application/json"
  226. },
  227. body: JSON.stringify({ username, password }),
  228. method: "POST"
  229. });
  230. const result = await response?.json();
  231. if (result?.error) {
  232. console.error(result?.error);
  233. return null;
  234. }
  235. // 设置用户信息
  236. this.id = result?.objectId;
  237. this.sessionToken = result?.sessionToken;
  238. this.data = result; // 保存用户数据
  239. // 缓存用户信息
  240. console.log(result)
  241. localStorage.setItem("NCloud/dev/User",JSON.stringify(result))
  242. return this;
  243. }
  244. /** 登出 */
  245. async logout() {
  246. if (!this.sessionToken) {
  247. console.error("用户未登录");
  248. return;
  249. }
  250. const response = await fetch(`https://dev.fmode.cn/parse/logout`, {
  251. headers: {
  252. "x-parse-application-id": "dev",
  253. "x-parse-session-token": this.sessionToken
  254. },
  255. method: "POST"
  256. });
  257. let result = await response?.json();
  258. if (result?.error) {
  259. console.error(result?.error);
  260. if(result?.error=="Invalid session token"){
  261. this.clearUserCache()
  262. return true;
  263. }
  264. return false;
  265. }
  266. this.clearUserCache()
  267. return true;
  268. }
  269. clearUserCache(){
  270. // 清除用户信息
  271. localStorage.removeItem("NCloud/dev/User")
  272. this.id = null;
  273. this.sessionToken = null;
  274. this.data = {};
  275. }
  276. /** 注册 */
  277. async signUp(username: string, password: string, additionalData: Record<string, any> = {}) {
  278. const userData = {
  279. username,
  280. password,
  281. ...additionalData // 合并额外的用户数据
  282. };
  283. const response = await fetch(`https://dev.fmode.cn/parse/users`, {
  284. headers: {
  285. "x-parse-application-id": "dev",
  286. "Content-Type": "application/json"
  287. },
  288. body: JSON.stringify(userData),
  289. method: "POST"
  290. });
  291. const result = await response?.json();
  292. if (result?.error) {
  293. console.error(result?.error);
  294. return null;
  295. }
  296. // 设置用户信息
  297. // 缓存用户信息
  298. console.log(result)
  299. localStorage.setItem("NCloud/dev/User",JSON.stringify(result))
  300. this.id = result?.objectId;
  301. this.sessionToken = result?.sessionToken;
  302. this.data = result; // 保存用户数据
  303. return this;
  304. }
  305. override async save() {
  306. let method = "POST";
  307. let url = `https://dev.fmode.cn/parse/users`;
  308. // 更新用户信息
  309. if (this.id) {
  310. url += `/${this.id}`;
  311. method = "PUT";
  312. }
  313. let data:any = JSON.parse(JSON.stringify(this.data))
  314. delete data.createdAt
  315. delete data.updatedAt
  316. delete data.ACL
  317. delete data.objectId
  318. const body = JSON.stringify(data);
  319. let headersOptions:any = {
  320. "content-type": "application/json;charset=UTF-8",
  321. "x-parse-application-id": "dev",
  322. "x-parse-session-token": this.sessionToken, // 添加sessionToken以进行身份验证
  323. }
  324. const response = await fetch(url, {
  325. headers: headersOptions,
  326. body: body,
  327. method: method,
  328. mode: "cors",
  329. credentials: "omit"
  330. });
  331. const result = await response?.json();
  332. if (result?.error) {
  333. console.error(result?.error);
  334. }
  335. if (result?.objectId) {
  336. this.id = result?.objectId;
  337. }
  338. localStorage.setItem("NCloud/dev/User",JSON.stringify(this.data))
  339. return this;
  340. }
  341. }
  342. export class CloudApi{
  343. async fetch(path:string,body:any,options?:{
  344. method:string
  345. body:any
  346. }){
  347. let reqOpts:any = {
  348. headers: {
  349. "x-parse-application-id": "dev",
  350. "Content-Type": "application/json"
  351. },
  352. method: options?.method || "POST",
  353. mode: "cors",
  354. credentials: "omit"
  355. }
  356. if(body||options?.body){
  357. reqOpts.body = JSON.stringify(body || options?.body);
  358. reqOpts.json = true;
  359. }
  360. let host = `https://dev.fmode.cn`
  361. // host = `http://127.0.0.1:1337`
  362. let url = `${host}/api/`+path
  363. console.log(url,reqOpts)
  364. const response = await fetch(url,reqOpts);
  365. let json = await response.json();
  366. return json
  367. }
  368. }