Repository navigation
Expand file tree
/
Copy pathapp.js
More file actions
57 lines (55 loc) · 2.67 KB
/
Copy pathapp.js
File metadata and controls
57 lines (55 loc) · 2.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
const API_BASE = '/api';
const Store = {
get(key, fallback=null){
try { const v = localStorage.getItem(key); return v ? JSON.parse(v) : fallback; }
catch { return fallback; }
},
set(key,value){ localStorage.setItem(key, JSON.stringify(value)); },
del(key){ localStorage.removeItem(key); }
};
const C2 = {
meKey: 'c2_forum_me',
me(){ return Store.get(this.meKey, null); },
setMe(u){ Store.set(this.meKey, u); },
logout(){ Store.del(this.meKey); location.href='index.html'; },
async _json(path, options={}){
const res = await fetch(API_BASE + path, {
headers:{'Content-Type':'application/json'},
...options
});
if(!res.ok){
const txt = await res.text().catch(()=>'');
throw new Error(txt || ('请求失败 ' + res.status));
}
return res.json();
},
login(ident,password){
return this._json('/users',{method:'POST',body:JSON.stringify({action:'login',ident,password})});
},
register({username,email,phone,password}){
return this._json('/users',{method:'POST',body:JSON.stringify({action:'register',username,email,phone,password})});
},
listUsers(){ return this._json('/users?list=1'); },
createUser({username,password}){
return this._json('/users',{method:'POST',body:JSON.stringify({action:'create',username,password})});
},
removeUser(username){
return this._json('/users',{method:'POST',body:JSON.stringify({action:'remove_user',username})});
},
setName(oldName,newName){
return this._json('/users',{method:'POST',body:JSON.stringify({action:'set_name',old:oldName,newname:newName})});
},
setPassword(username,password){
return this._json('/users',{method:'POST',body:JSON.stringify({action:'set_password',username,password})});
},
listCategories(){ return this._json('/posts?cats=1'); },
addCategory(name){ return this._json('/posts',{method:'POST',body:JSON.stringify({action:'add_category',name})}); },
delCategory(name){ return this._json('/posts',{method:'POST',body:JSON.stringify({action:'del_category',name})}); },
listPosts(){ return this._json('/posts'); },
createPost(data){ return this._json('/posts',{method:'POST',body:JSON.stringify({action:'create',...data})}); },
likePost(id,user){ return this._json('/posts',{method:'POST',body:JSON.stringify({action:'like',id,user})}); },
commentPost(id,user,text){ return this._json('/posts',{method:'POST',body:JSON.stringify({action:'comment',id,user,text})}); },
deletePost(id){ return this._json('/posts',{method:'POST',body:JSON.stringify({action:'delete',id})}); },
listShared(){ return this._json('/shared'); },
uploadShared(file){ return this._json('/shared',{method:'POST',body:JSON.stringify({action:'upload',...file})}); }
};