-
Notifications
You must be signed in to change notification settings - Fork 7
/
account.ts
78 lines (68 loc) · 1.7 KB
/
account.ts
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
import { v4 as uuidv4 } from "uuid"
import { getAccessToken } from "/lib/authentication"
const BASE_URL = "https://tmc.mooc.fi/api/v8"
export function createAccount(data: any) {
data.username = uuidv4()
const body = {
user: data,
user_field: {
first_name: data.first_name,
last_name: data.last_name,
},
origin: "mooc.fi",
language: "fi",
}
return new Promise((resolve, reject) => {
fetch(`${BASE_URL}/users`, {
body: JSON.stringify(body),
method: "POST",
headers: {
"Content-Type": "application/json",
},
}).then((res) => {
res.json().then((json) => {
if (!json.success) {
reject(json.errors)
} else {
resolve(json)
}
})
})
})
}
export async function updateAccount(firstName: string, lastName: string) {
const accessToken = getAccessToken(undefined)
if (!accessToken) {
throw new Error("not logged in?")
}
const res = await fetch(
`${BASE_URL}/users/current?show_user_fields=1&extra_fields=1`,
{
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
},
)
if (!res.ok) {
throw new Error("error fetching existing user")
}
const existingUser = await res.json()
const newUser = {
...existingUser,
user_field: {
...existingUser.user_field,
first_name: firstName,
last_name: lastName,
},
}
const newRes = await fetch(`${BASE_URL}/users/${existingUser.id}`, {
method: "PUT",
body: JSON.stringify(newUser),
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
})
return await newRes.json()
}