1 | const dfn = require('@netlify/open-api')
|
2 | const get = require('lodash.get')
|
3 | const set = require('lodash.set')
|
4 | const pWaitFor = require('p-wait-for')
|
5 |
|
6 | const deploy = require('./deploy')
|
7 | const { addMethods } = require('./methods')
|
8 | const { getOperations } = require('./operations')
|
9 |
|
10 | class NetlifyAPI {
|
11 | constructor(accessToken, opts) {
|
12 | addMethods(this)
|
13 |
|
14 |
|
15 | if (typeof accessToken === 'object') {
|
16 | opts = accessToken
|
17 | accessToken = null
|
18 | }
|
19 |
|
20 | opts = Object.assign(
|
21 | {
|
22 | userAgent: 'netlify/js-client',
|
23 | scheme: dfn.schemes[0],
|
24 | host: dfn.host,
|
25 | pathPrefix: dfn.basePath,
|
26 | accessToken,
|
27 | globalParams: {}
|
28 | },
|
29 | opts
|
30 | )
|
31 |
|
32 | this.defaultHeaders = {
|
33 | 'User-agent': opts.userAgent,
|
34 | accept: 'application/json'
|
35 | }
|
36 |
|
37 | this.scheme = opts.scheme
|
38 | this.host = opts.host
|
39 | this.pathPrefix = opts.pathPrefix
|
40 | this.globalParams = opts.globalParams
|
41 | this.accessToken = opts.accessToken
|
42 | this.agent = opts.agent
|
43 | }
|
44 |
|
45 | get accessToken() {
|
46 | return (get(this, 'defaultHeaders.Authorization') || '').replace('Bearer ', '') || null
|
47 | }
|
48 |
|
49 | set accessToken(token) {
|
50 | if (token) {
|
51 | set(this, 'defaultHeaders.Authorization', 'Bearer ' + token)
|
52 | } else {
|
53 | delete this.defaultHeaders.Authorization
|
54 | }
|
55 | }
|
56 |
|
57 | get basePath() {
|
58 | return `${this.scheme}://${this.host}${this.pathPrefix}`
|
59 | }
|
60 |
|
61 | async getAccessToken(ticket, opts) {
|
62 | opts = Object.assign({ poll: 1000, timeout: 3.6e6 }, opts)
|
63 |
|
64 | const api = this
|
65 |
|
66 | const { id } = ticket
|
67 |
|
68 | let authorizedTicket
|
69 | const checkTicket = async () => {
|
70 | const t = await api.showTicket({ ticketId: id })
|
71 | if (t.authorized) {
|
72 | authorizedTicket = t
|
73 | }
|
74 | return !!t.authorized
|
75 | }
|
76 |
|
77 | await pWaitFor(checkTicket, {
|
78 | interval: opts.poll,
|
79 | timeout: opts.timeout,
|
80 | message: 'Timeout while waiting for ticket grant'
|
81 | })
|
82 |
|
83 | const accessTokenResponse = await api.exchangeTicket({ ticketId: authorizedTicket.id })
|
84 |
|
85 | this.accessToken = accessTokenResponse.access_token
|
86 | return accessTokenResponse.access_token
|
87 | }
|
88 |
|
89 | async deploy(siteId, buildDir, opts) {
|
90 | if (!this.accessToken) throw new Error('Missing access token')
|
91 |
|
92 |
|
93 | return await deploy(this, siteId, buildDir, opts)
|
94 | }
|
95 | }
|
96 |
|
97 | module.exports = NetlifyAPI
|
98 |
|
99 | module.exports.methods = getOperations()
|