ncloud.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412
  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. const result = await response?.json();
  258. if (result?.error) {
  259. console.error(result?.error);
  260. return false;
  261. }
  262. // 清除用户信息
  263. localStorage.removeItem("NCloud/dev/User")
  264. this.id = null;
  265. this.sessionToken = null;
  266. this.data = {};
  267. return true;
  268. }
  269. /** 注册 */
  270. async signUp(username: string, password: string, additionalData: Record<string, any> = {}) {
  271. const userData = {
  272. username,
  273. password,
  274. ...additionalData // 合并额外的用户数据
  275. };
  276. const response = await fetch(`https://dev.fmode.cn/parse/users`, {
  277. headers: {
  278. "x-parse-application-id": "dev",
  279. "Content-Type": "application/json"
  280. },
  281. body: JSON.stringify(userData),
  282. method: "POST"
  283. });
  284. const result = await response?.json();
  285. if (result?.error) {
  286. console.error(result?.error);
  287. return null;
  288. }
  289. // 设置用户信息
  290. // 缓存用户信息
  291. console.log(result)
  292. localStorage.setItem("NCloud/dev/User",JSON.stringify(result))
  293. this.id = result?.objectId;
  294. this.sessionToken = result?.sessionToken;
  295. this.data = result; // 保存用户数据
  296. return this;
  297. }
  298. override async save() {
  299. let method = "POST";
  300. let url = `https://dev.fmode.cn/parse/users`;
  301. // 更新用户信息
  302. if (this.id) {
  303. url += `/${this.id}`;
  304. method = "PUT";
  305. }
  306. let data:any = JSON.parse(JSON.stringify(this.data))
  307. delete data.createdAt
  308. delete data.updatedAt
  309. delete data.ACL
  310. delete data.objectId
  311. const body = JSON.stringify(data);
  312. let headersOptions:any = {
  313. "content-type": "application/json;charset=UTF-8",
  314. "x-parse-application-id": "dev",
  315. "x-parse-session-token": this.sessionToken, // 添加sessionToken以进行身份验证
  316. }
  317. const response = await fetch(url, {
  318. headers: headersOptions,
  319. body: body,
  320. method: method,
  321. mode: "cors",
  322. credentials: "omit"
  323. });
  324. const result = await response?.json();
  325. if (result?.error) {
  326. console.error(result?.error);
  327. }
  328. if (result?.objectId) {
  329. this.id = result?.objectId;
  330. }
  331. localStorage.setItem("NCloud/dev/User",JSON.stringify(this.data))
  332. return this;
  333. }
  334. }
  335. export class CloudApi{
  336. async fetch(path:string,body:any,options?:{
  337. method:string
  338. body:any
  339. }){
  340. let reqOpts:any = {
  341. headers: {
  342. "x-parse-application-id": "dev",
  343. "Content-Type": "application/json"
  344. },
  345. method: options?.method || "POST",
  346. mode: "cors",
  347. credentials: "omit"
  348. }
  349. if(body||options?.body){
  350. reqOpts.body = JSON.stringify(body || options?.body);
  351. reqOpts.json = true;
  352. }
  353. let host = `https://dev.fmode.cn`
  354. // host = `http://127.0.0.1:1337`
  355. let url = `${host}/api/`+path
  356. console.log(url,reqOpts)
  357. const response = await fetch(url,reqOpts);
  358. let json = await response.json();
  359. return json
  360. }
  361. }