forked from cs10/node-canvas-lms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
canvas.js
92 lines (79 loc) · 2.45 KB
/
canvas.js
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
'use strict';
var request = require('request');
var resolve = require('url').resolve;
function Canvas(host, options) {
options = options || {};
this.name = 'canvas' || options.name;
this.accessToken = options.accessToken || options.token || '';
this.apiVersion = options.apiVersion || options.version || 'v1';
this.host = host;
}
function isHttpClientError(response) {
return (response.statusCode >= 400 && response.statusCode < 500);
}
function isHttpError(response) {
return (isHttpClientError(response) || isHttpServerError(response));
}
function isHttpServerError(response) {
return (response.statusCode >= 500 && response.statusCode < 600);
}
Canvas.prototype._buildApiUrl = function(endpoint) {
if (endpoint.substring(0, 1) != '/') {
endpoint = '/' + endpoint;
}
return resolve(this.host, '/api/' + this.apiVersion + endpoint);
};
Canvas.prototype._http = function(options, callback) {
options.headers = {
Authorization: 'Bearer ' + this.accessToken
};
options.json = true;
options.useQuerystring = true;
return request(options, function(error, response, body) {
return callback(error, response, body);
});
};
Canvas.prototype.delete = function(endpoint, querystring) {
var options = {
method: 'DELETE',
url: this._buildApiUrl(endpoint),
qs: querystring
};
return this._http(options);
};
Canvas.prototype.get = function(endpoint, querystring, callback) {
var options = {
method: 'GET',
url: this._buildApiUrl(endpoint),
qs: querystring
};
return this._http(options, callback);
};
Canvas.prototype.post = function(endpoint, querystring, form, callback) {
var options = {
method: 'POST',
url: this._buildApiUrl(endpoint),
qs: querystring,
form: form
};
return this._http(options, callback);
};
Canvas.prototype.put = function(endpoint, querystring, form, callback) {
var options = {
method: 'PUT',
url: this._buildApiUrl(endpoint),
qs: querystring,
form: form,
};
return this._http(options, callback);
};
Canvas.prototype.getID = function(idType, id, callback) {
var endpoint = 'users/' + (idType ? idType + ':' : '') + id + '/profile';
return this.get(endpoint, '', function(body) {
if (body.errors) {
return callback(body.errors);
}
return callback(body.id);
});
}
module.exports = Canvas;