about summary refs log tree commit diff
path: root/usth/ICT3.2/prac/5/2.js
blob: 04969437daf20ee78f289f2c3ba0f9f062f9ee70 (plain) (blame)
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
const BASE = `https://dummyapi.io/data/api/`

function get_collection(collection) {
    let request = new XMLHttpRequest();
    request.open('GET', `${BASE}${collection}`);
    request.setRequestHeader('app-id', '5f76987a523f015e7c5ae49b');
    request.onload = function () {
        let prefix = collection.includes('/') ? '' : `<h1>${collection}s</h1>`;
        document.getElementById(collection).innerHTML = (
             prefix + JSON.parse(request.response).data.map(
                function (member) {
                    let c = collection.slice(-4);
                    let id = member.id;
                    if (c == 'post')
                        id += '/comment';

                    let call = `"get_member('${c}', '${id}')"`;
                    if (c == 'post')
                        return `<button onclick=${call}/>${member.text}</button>
                                <div id=${id}></div>`;

                    let repr = `${member.firstName} ${member.lastName}`;
                    return `<div id=${id}>
                              <button onclick=${call}/>${repr}</button>
                            </div>`;
                }).join("\n"));
    }
    request.send();
}

function user_format(r) {
    let l = r.location;
    return `<h2>${r.title} ${r.firstName} ${r.lastName}</h2>
            <div id='user/${r.id}/post'>
              <button onclick="get_collection('user/${r.id}/post')">
                List posts
              </button>
            </div>
            <p>gender: ${r.gender}</p>
            <p>email: ${r.email}</p>
            <p>date of birth: ${r.dateOfBirth}</p>
            <p>register date: ${r.registerDate}</p>
            <p>phone: ${r.phone}</p>
            <p>picture: ${r.picture}</p>
            <p>location: ${l.street}, ${l.city}, ${l.state}, ${l.country}</p>`
}

function post_format(r) {
    return r.data.map(comment => `<p>${comment.message}</p>`).join("\n");
}

function get_member(collection, member) {
    let request = new XMLHttpRequest();
    console.log(`${BASE}${collection}/${member}`);
    request.open('GET', `${BASE}${collection}/${member}`);
    request.setRequestHeader('app-id', '5f76987a523f015e7c5ae49b');
    request.onload = function () {
        let format = collection == 'user' ? user_format : post_format;
        document.getElementById(member).innerHTML = format(
            JSON.parse(request.response));
    }
    request.send();
}