summaryrefslogtreecommitdiff
path: root/school/node_modules/pronote-api/src/server/index.js
blob: 1693e1c54689490566e9b4d620120401236ec2dd (plain)
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
const { graphql } = require('graphql');

const http = require('./http');
const context = require('./context');
const getSchemas = require('./schemas');
const { login, logout, getSession } = require('./auth');

async function start(host, port)
{
    const schemas = await getSchemas();

    await http(host, port, {
        graphql: ({ query, variables }, token) => handle(token, schemas, query, context, variables),
        login: params => login(params),
        logout: (_, token) => logout(token)
    });
}

async function handle(token, schemas, query, context, variables)
{
    if (!token) {
        throw {
            http: 401,
            message: 'Missing \'Token\' header'
        };
    }

    if (!query) {
        throw {
            http: 400,
            message: 'Missing \'query\' field or \'Content-Type: application/json\' header'
        };
    }

    const session = getSession(token);
    if (!session) {
        throw {
            http: 401,
            message: 'Unknown session token'
        };
    }

    const schema = schemas[session.type.name];
    return await graphql(schema, query, context(session), null, variables);
}

module.exports = start;