/
index.coffee
86 lines (73 loc) · 2.26 KB
/
index.coffee
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
querystring = require 'querystring'
request = require 'superagent'
authBaseUrl = 'https://quizlet.com/authorize/'
tokenUrl = 'https://api.quizlet.com/oauth/token'
baseUrl = 'https://api.quizlet.com/2.0/'
module.exports = class QuizletAPI
###
Interface to the Quizlet API.
###
constructor: (params) ->
###
Creates a new instance of a Quizlet API accessor.
###
@clientId = if params.clientId? then params.clientId else throw new Error 'Need client ID!'
@secret = if params.secret? then params.secret else throw new Error 'Need secret!'
getAuthUrl: (scopes = ['read'], state = 'state', redirectURI) ->
###
Gets an authorize URL to use to auth a user.
###
for scope, i in scopes
scopes[i] = scope = scope.toLowerCase()
unless scope in ['read', 'write_set', 'write_group']
throw new Error "Invalid scope `#{scope}` encountered!"
params =
client_id: @clientId
response_type: 'code'
scope: escape scopes.join ' '
state: state
if redirectUri?
params.redirect_uri = redirectUri
return authBaseUrl + '?' + querystring.stringify(params)
requestToken: (code, redirectUri) ->
###
Requests a token from Quizlet.
###
basic = new Buffer(@clientId + ':' + @secret).toString 'base64'
params =
grant_type: 'authorization_code'
code: code
request.post(tokenUrl)
.type('form')
.set('Authorization', 'Basic ' + basic)
.send()
.end (res) ->
if res.body.error
cb true, res.body
else
cb null, res.body
get: (resource, params, cb) ->
###
Performs a general GET request against the Quizlet API.
###
params.client_id = @clientId
request.get(baseUrl + resource + '?' + querystring.stringify(params)).end (res) ->
if res.body.error
cb true, res.body
else
cb null, res.body
getUser: (username, cb) ->
###
Gets information about the given user.
###
@get "users/#{username}", {}, cb
getUserSets: (username, cb) ->
###
Gets the sets of the given user.
###
@get "users/#{username}/sets", {}, cb
getUserFavorites: (username, cb) ->
###
Gets the favorite sets of the given user.
###
@get "users/#{username}/favorites", {}, cb