-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
Copy pathsave-project-to-server.js
63 lines (62 loc) · 2.54 KB
/
save-project-to-server.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
import queryString from 'query-string';
import xhr from 'xhr';
import storage from '../lib/storage';
/**
* Save a project JSON to the project server.
* This should eventually live in scratch-www.
* @param {number} projectId the ID of the project, null if a new project.
* @param {object} vmState the JSON project representation.
* @param {object} params the request params.
* @property {?number} params.originalId the original project ID if a copy/remix.
* @property {?boolean} params.isCopy a flag indicating if this save is creating a copy.
* @property {?boolean} params.isRemix a flag indicating if this save is creating a remix.
* @property {?string} params.title the title of the project.
* @return {Promise} A promise that resolves when the network request resolves.
*/
export default function (projectId, vmState, params) {
const opts = {
body: vmState,
// If we set json:true then the body is double-stringified, so don't
headers: {
'Content-Type': 'application/json'
},
withCredentials: true
};
const creatingProject = projectId === null || typeof projectId === 'undefined';
const queryParams = {};
if (Object.prototype.hasOwnProperty.call(params, 'originalId')) queryParams.original_id = params.originalId;
if (Object.prototype.hasOwnProperty.call(params, 'isCopy')) queryParams.is_copy = params.isCopy;
if (Object.prototype.hasOwnProperty.call(params, 'isRemix')) queryParams.is_remix = params.isRemix;
if (Object.prototype.hasOwnProperty.call(params, 'title')) queryParams.title = params.title;
let qs = queryString.stringify(queryParams);
if (qs) qs = `?${qs}`;
if (creatingProject) {
Object.assign(opts, {
method: 'post',
url: `${storage.projectHost}/${qs}`
});
} else {
Object.assign(opts, {
method: 'put',
url: `${storage.projectHost}/${projectId}${qs}`
});
}
return new Promise((resolve, reject) => {
xhr(opts, (err, response) => {
if (err) return reject(err);
if (response.statusCode !== 200) return reject(response.statusCode);
let body;
try {
// Since we didn't set json: true, we have to parse manually
body = JSON.parse(response.body);
} catch (e) {
return reject(e);
}
body.id = projectId;
if (creatingProject) {
body.id = body['content-name'];
}
resolve(body);
});
});
}