-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
193 lines (152 loc) · 5.09 KB
/
index.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
const httpHeaders = require( 'http-headers' )
const DefaultTransporter = require( 'google-auth-library' ).DefaultTransporter
const buildURL = require( 'axios/lib/helpers/buildURL' )
const transformData = require( 'axios/lib/core/transformData' )
const settle = require( 'axios/lib/core/settle' )
const GOOGLE_API_BASE = 'https://www.googleapis.com'
const BOUNDARY_REGEXP = /^multipart\/mixed;\s*boundary=(?:"([^"]+)"|(.+)$)/i
const { URL } = 'URL' in global ? global : require( 'url' )
class Batch {
constructor( auth ) {
this.auth = auth
this.apiPath = ''
this.requestCount = 0
this.requests = {}
this.transporter = new DefaultTransporter
this.request = this.request.bind( this )
}
static build( request, index ) {
request = { headers: {}, ...request }
let url = request.uri || request.url
if ( request.params ) {
url = buildURL( url, request.params, request.paramsSerializer )
}
let data = transformData(
request.data,
request.headers,
request.transformRequest
)
let path = 0 === url.indexOf( GOOGLE_API_BASE + '/' )
? url.slice( GOOGLE_API_BASE.length )
: ( () => { throw new Error( 'Invalid URL' ) } )()
let body = [
`${request.method} ${path}`,
`${Object.entries( request.headers ).map( ( [ name, value ] ) => `${name}: ${value}` ).join( '\r\n' )}`,
]
if ( data ) {
body.push( '', data )
}
return [
'Content-Type: application/http',
`Content-ID: ${request.requestId}`,
'',
].concat( body ).join( '\r\n' )
}
adapter( config ) {
return new Promise( ( resolve, reject ) => {
if ( config.requestId in this.requests ) {
return reject( new Error( 'googleapis-batch: Duplicate Request ID' ) )
}
this.requests[config.requestId] = {
config,
resolve,
reject,
}
} )
}
request( config, callback ) {
config.requestId = config.requestId || `request-${this.requestCount++}`
const { pathname } = new URL( config.url )
const apiPath = pathname.split( '/' ).slice( 0, 3 ).join( '/' )
if ( ! this.apiPath ) {
this.apiPath = apiPath
} else if ( this.apiPath !== apiPath ) {
throw new Error( 'Requests must all go to the same API. Use separate Batch instances for separate APIs.' )
}
config.adapter = this.adapter.bind( this )
return this.transporter.request( config, callback )
}
exec( callback ) {
// When making requests, Axios starts by setting up a
// Promise chain starting with Promise.resolve()
// https://github.com/axios/axios/blob/0b3db5d87a60a1ad8b0dce9669dbc10483ec33da/lib/core/Axios.js#L39-L53
// Since this.exec() is almost certainly called on the
// same tick as this.request(), we need to also start
// this.exec() with a Promise.resolve() so that it gets
// appended to the microtask queue. Otherwise, this.exec()
// will fire before the Promises in this.adapter()
// are instantiated/added to this.requests()
return Promise.resolve().then( () => {
const random = ( Math.random() * 10000000000000000 + 1000000000000000 ).toString().slice( 0, 16 )
const boundary = `batch_${random}`
const encapsulation = `\r\n\r\n--${boundary}\r\n`
return this.auth.request( {
url: `${GOOGLE_API_BASE}/batch${this.apiPath}`,
method: 'post',
headers: {
'Content-Type': `multipart/mixed; boundary=${boundary}`
},
data: [ '' ].concat( Object.values( this.requests ).map( request => Batch.build( request.config ) ) ).join( encapsulation ) + `\r\n\r\n--${boundary}--`,
responseType: 'text',
} )
.then( response => {
return this.response( response, callback )
} )
.catch( err => {
if ( callback ) {
return callback( err )
}
throw err
} )
} )
}
response( multiResponse, multiCallback ) {
const throwCallback = err => {
if ( multiCallback ) {
return multiCallback( err )
}
throw err
}
const { headers: { 'content-type': ContentType } } = multiResponse
let boundary = BOUNDARY_REGEXP.exec( ContentType )
if ( ! boundary ) {
return throwCallback( new Error( 'No multipart boundary found' ) )
}
boundary = boundary[1] || boundary[2]
const parts = `\r\n${multiResponse.data}`.split( `\r\n--${boundary}--` )[0].split( `\r\n--${boundary}\r\n` ).slice( 1 )
for ( let part of parts ) {
let [ meta, headers, body ] = part.split( '\r\n\r\n' )
const metaHeaders = httpHeaders( meta, true )
const requestId = metaHeaders['content-id'].replace( 'response-', '' )
const request = this.requests[requestId]
if ( ! request ) {
return throwCallback( new Error( 'Unknown Batch Response Item' ) )
}
const { config, resolve, reject } = request
if ( 'application/http' !== metaHeaders['content-type'] ) {
reject( new Error( 'Unknown Batch Response Item Format' ) )
break
}
const partHeaders = httpHeaders( headers )
const response = {
status: partHeaders.statusCode,
statusText: partHeaders.statusMessage,
headers: partHeaders.headers,
config,
request: 'batch',
data: body,
}
settle(
resolve,
reject,
response
)
}
if ( multiCallback ) {
multiCallback( null, multiResponse )
} else {
return multiResponse
}
}
}
module.exports = Batch