This repository has been archived by the owner on Dec 26, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
submit.js
241 lines (198 loc) · 6.04 KB
/
submit.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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
const express = require('express');
const GitHubApi = require('@octokit/rest');
const _ = require('lodash');
const bodyParser = require('body-parser');
const winston = require('winston');
const logger = winston.createLogger({
level: 'debug',
transports: [
new winston.transports.File({ filename: 'combined.log' })
]
});
// The /submit endpoint creates a new pull request based on openaddresses/openaddresses
// master with a file containing the contents of the POST body
function postBodyErrorHandler(err, req, res, next) {
if (_.get(err, 'type') === 'entity.parse.failed') {
res.status(400).type('application/json').send({
error: {
code: 400,
message: `POST body not parseable as JSON: ${err.body}`
}
});
} else if (_.get(err, 'type') === 'entity.too.large') {
res.status(400).type('application/json').send({
error: {
code: 400,
message: 'POST body exceeds max size of 50kb'
}
});
} else {
next();
}
}
// verify that req.body contains an actual JSON object
function preconditionsCheck(req, res, next) {
if (!process.env.GITHUB_ACCESS_TOKEN) {
res.status(500).type('application/json').send({
error: {
code: 500,
message: 'GITHUB_ACCESS_TOKEN not defined in process environment'
}
});
} else if (_.isEmpty(req.body)) {
logger.error('POST body empty');
res.status(400).type('application/json').send({
error: {
code: 400,
message: 'POST body empty'
}
});
} else {
next();
}
}
// login to github
function authenticateWithGithub(req, res, next) {
res.locals.github = new GitHubApi();
res.locals.github.authenticate({
type: 'oauth',
token: process.env.GITHUB_ACCESS_TOKEN
});
next();
}
// generate a "unique" target reference name and upload file path for this source
function uniqueifyNames(req, res, next) {
// create a random number to hopefully generate a unique branch name and filename
const uniqueHexNumber = _.random(255, 255*255*255).toString(16);
// this is the reference/branch name that will be created
res.locals.reference_name = `submit_service_${uniqueHexNumber}`;
// this is the file that will be added
res.locals.path = `sources/contrib/source_${uniqueHexNumber}.json`;
next();
}
// lookup the master openaddresses/openaddresses SHA and create a reference (branch)
// to it that can be used for this source
async function branchFromMaster(req, res, next) {
// lookup the sha of openaddresses/openaddresses#master
// masterReferenceResponse.data.object.sha is needed when creating a reference
let masterReferenceResponse;
try {
masterReferenceResponse = await res.locals.github.gitdata.getReference({
owner: 'openaddresses',
repo: 'openaddresses',
ref: 'heads/master'
});
}
catch (err) {
logger.error(`Error looking up master reference: ${err}`);
res.status(500).type('application/json').send({
error: {
code: 500,
message: `Error looking up master reference: ${err}`
}
});
return;
}
try {
await res.locals.github.gitdata.createReference({
owner: 'openaddresses',
repo: 'openaddresses',
ref: `refs/heads/${res.locals.reference_name}`,
sha: masterReferenceResponse.data.object.sha
});
next();
}
catch (err) {
logger.error(`Error creating local reference: ${err}`);
res.status(500).type('application/json').send({
error: {
code: 500,
message: `Error creating local reference: ${err}`
}
});
return;
}
}
// take the POST body of this request and add it as a file to the branch
async function addFileToBranch(req, res, next) {
try {
// remove the source_data field that was returned by /sample
const body = _.omit(req.body, 'source_data');
// temporary fixes for null
delete body.test;
delete body.website;
if (_.has(body, 'license')) {
body.license = _.pickBy(body.license, _.negate(_.isNull));
}
body.coverage = {
country: 'xx'
};
// end of temporary fixes for null
await res.locals.github.repos.createFile({
owner: 'openaddresses',
repo: 'openaddresses',
path: res.locals.path,
message: 'This file was added by the OpenAddresses submit-service',
content: Buffer.from(JSON.stringify(body, null, 4)).toString('base64'),
branch: res.locals.reference_name
});
next();
}
catch (err) {
logger.error(`Error creating file for reference: ${err}`);
res.status(500).type('application/json').send({
error: {
code: 500,
message: `Error creating file for reference: ${err}`
}
});
}
}
// create a pull request which will get picked up by the machine
async function createPullRequest(req, res, next) {
try {
const response = await res.locals.github.pullRequests.create({
owner: 'openaddresses',
repo: 'openaddresses',
title: 'Submit Service Pull Request',
head: `openaddresses:${res.locals.reference_name}`,
base: 'master',
body: 'This pull request contains changes requested by the Submit Service',
maintainer_can_modify: true
});
// create pull request was successful so extract the url and set into locals
res.locals.pullRequestUrl = response.data.html_url;
next();
} catch (err) {
logger.error(`Error creating pull request: ${err}`);
res.status(500).type('application/json').send({
error: {
code: 500,
message: `Error creating pull request: ${err}`
}
});
}
}
// send the pull request URL back to the caller
function output(req, res, next) {
// entire github pipeline was successful so return the PR URL
res.status(200).type('application/json').send({
response: {
url: res.locals.pullRequestUrl
}
});
}
module.exports = express.Router()
.use(bodyParser.json({
limit: '50kb'
}))
.use(postBodyErrorHandler)
.post('/', [
preconditionsCheck,
authenticateWithGithub,
uniqueifyNames,
branchFromMaster,
addFileToBranch,
createPullRequest,
output
]);