Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit 85c8441

Browse files
authoredDec 4, 2020
Merge pull request #1694 from Swapnil-2001/async-await-refactor
Refactor examples.js to use async/await
2 parents f3079ed + 361ee9d commit 85c8441

File tree

1 file changed

+152
-163
lines changed

1 file changed

+152
-163
lines changed
 

‎server/scripts/examples.js

Lines changed: 152 additions & 163 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@ import Q from 'q';
33
import mongoose from 'mongoose';
44
import objectID from 'bson-objectid';
55
import shortid from 'shortid';
6-
import eachSeries from 'async/eachSeries';
76
import User from '../models/user';
87
import Project from '../models/project';
98

@@ -46,7 +45,7 @@ mongoose.connection.on('error', () => {
4645
process.exit(1);
4746
});
4847

49-
function getCategories() {
48+
async function getCategories() {
5049
const categories = [];
5150
const options = {
5251
url: 'https://api.github.com/repos/processing/p5.js-website/contents/src/data/examples/en',
@@ -57,23 +56,23 @@ function getCategories() {
5756
},
5857
json: true
5958
};
60-
return rp(options).then((res) => {
59+
try {
60+
const res = await rp(options);
6161
res.forEach((metadata) => {
6262
let category = '';
6363
for (let j = 1; j < metadata.name.split('_').length; j += 1) {
6464
category += `${metadata.name.split('_')[j]} `;
6565
}
6666
categories.push({ url: metadata.url, name: category.trim() });
6767
});
68-
6968
return categories;
70-
}).catch((err) => {
71-
throw err;
72-
});
69+
} catch (error) {
70+
throw error;
71+
}
7372
}
7473

7574
function getSketchesInCategories(categories) {
76-
return Q.all(categories.map((category) => {
75+
return Q.all(categories.map(async (category) => {
7776
const options = {
7877
url: `${category.url.replace('?ref=main', '')}`,
7978
method: 'GET',
@@ -83,8 +82,8 @@ function getSketchesInCategories(categories) {
8382
},
8483
json: true
8584
};
86-
87-
return rp(options).then((res) => {
85+
try {
86+
const res = await rp(options);
8887
const projectsInOneCategory = [];
8988
res.forEach((example) => {
9089
let projectName;
@@ -103,14 +102,14 @@ function getSketchesInCategories(categories) {
103102
}
104103
});
105104
return projectsInOneCategory;
106-
}).catch((err) => {
107-
throw err;
108-
});
105+
} catch (error) {
106+
throw error;
107+
}
109108
}));
110109
}
111110

112111
function getSketchContent(projectsInAllCategories) {
113-
return Q.all(projectsInAllCategories.map(projectsInOneCategory => Q.all(projectsInOneCategory.map((project) => {
112+
return Q.all(projectsInAllCategories.map(projectsInOneCategory => Q.all(projectsInOneCategory.map(async (project) => {
114113
const options = {
115114
url: `${project.sketchUrl.replace('?ref=main', '')}`,
116115
method: 'GET',
@@ -119,8 +118,8 @@ function getSketchContent(projectsInAllCategories) {
119118
Authorization: `Basic ${Buffer.from(`${clientId}:${clientSecret}`).toString('base64')}`
120119
}
121120
};
122-
123-
return rp(options).then((res) => {
121+
try {
122+
const res = await rp(options);
124123
const noNumberprojectName = project.projectName.replace(/(\d+)/g, '');
125124
if (noNumberprojectName === 'Instance Mode: Instance Container ') {
126125
for (let i = 0; i < 4; i += 1) {
@@ -134,9 +133,9 @@ function getSketchContent(projectsInAllCategories) {
134133
project.sketchContent = res;
135134
}
136135
return project;
137-
}).catch((err) => {
138-
throw err;
139-
});
136+
} catch (error) {
137+
throw error;
138+
}
140139
}))));
141140
}
142141

@@ -183,14 +182,13 @@ async function addAssetsToProject(assets, response, project) {
183182
};
184183

185184
// a function to await for the response that contains the content of asset file
186-
const doRequest = function (optionsAsset) {
187-
return new Promise(((resolve, reject) => {
188-
rp(optionsAsset).then((res) => {
189-
resolve(res);
190-
}).catch((err) => {
191-
reject(err);
192-
});
193-
}));
185+
const doRequest = async (optionsAsset) => {
186+
try {
187+
const res = await rp(optionsAsset);
188+
return res;
189+
} catch (error) {
190+
throw error;
191+
}
194192
};
195193

196194
assetContent = await doRequest(assetOptions);
@@ -225,7 +223,7 @@ async function addAssetsToProject(assets, response, project) {
225223
}
226224

227225

228-
function createProjectsInP5user(projectsInAllCategories) {
226+
async function createProjectsInP5user(projectsInAllCategories) {
229227
const options = {
230228
url: 'https://api.github.com/repos/processing/p5.js-website/contents/src/data/examples/assets',
231229
method: 'GET',
@@ -236,155 +234,146 @@ function createProjectsInP5user(projectsInAllCategories) {
236234
json: true
237235
};
238236

239-
rp(options).then((res) => {
240-
User.findOne({ username: 'p5' }, (err, user) => {
241-
if (err) throw err;
242-
243-
eachSeries(projectsInAllCategories, (projectsInOneCategory, categoryCallback) => {
244-
eachSeries(projectsInOneCategory, async (project, projectCallback) => {
245-
let newProject;
246-
const a = objectID().toHexString();
247-
const b = objectID().toHexString();
248-
const c = objectID().toHexString();
249-
const r = objectID().toHexString();
250-
const noNumberprojectName = project.projectName.replace(/(\d+)/g, '');
251-
if (noNumberprojectName === 'Instance Mode: Instance Container ') {
252-
newProject = new Project({
253-
name: project.projectName,
254-
user: user._id,
255-
files: [
256-
{
257-
name: 'root',
258-
id: r,
259-
_id: r,
260-
children: [a, b, c],
261-
fileType: 'folder'
262-
},
263-
{
264-
name: 'sketch.js',
265-
content: '// Instance Mode: Instance Container, please check its index.html file',
266-
id: a,
267-
_id: a,
268-
fileType: 'file',
269-
children: []
270-
},
271-
{
272-
name: 'index.html',
273-
content: project.sketchContent,
274-
isSelectedFile: true,
275-
id: b,
276-
_id: b,
277-
fileType: 'file',
278-
children: []
279-
},
280-
{
281-
name: 'style.css',
282-
content: defaultCSS,
283-
id: c,
284-
_id: c,
285-
fileType: 'file',
286-
children: []
287-
}
288-
],
289-
_id: shortid.generate()
290-
});
291-
} else {
292-
newProject = new Project({
293-
name: project.projectName,
294-
user: user._id,
295-
files: [
296-
{
297-
name: 'root',
298-
id: r,
299-
_id: r,
300-
children: [a, b, c],
301-
fileType: 'folder'
302-
},
303-
{
304-
name: 'sketch.js',
305-
content: project.sketchContent,
306-
id: a,
307-
_id: a,
308-
isSelectedFile: true,
309-
fileType: 'file',
310-
children: []
311-
},
312-
{
313-
name: 'index.html',
314-
content: defaultHTML,
315-
id: b,
316-
_id: b,
317-
fileType: 'file',
318-
children: []
319-
},
320-
{
321-
name: 'style.css',
322-
content: defaultCSS,
323-
id: c,
324-
_id: c,
325-
fileType: 'file',
326-
children: []
327-
}
328-
],
329-
_id: shortid.generate()
330-
});
331-
}
332-
333-
const assetsInProject = project.sketchContent.match(/assets\/[\w-]+\.[\w]*/g)
334-
|| project.sketchContent.match(/asset\/[\w-]*/g) || [];
237+
try {
238+
const res = await rp(options);
239+
const user = await User.findOne({ username: 'p5' }).exec();
240+
await Q.all(projectsInAllCategories.map(projectsInOneCategory => Q.all(projectsInOneCategory.map(async (project) => {
241+
let newProject;
242+
const a = objectID().toHexString();
243+
const b = objectID().toHexString();
244+
const c = objectID().toHexString();
245+
const r = objectID().toHexString();
246+
const noNumberprojectName = project.projectName.replace(/(\d+)/g, '');
247+
if (noNumberprojectName === 'Instance Mode: Instance Container ') {
248+
newProject = new Project({
249+
name: project.projectName,
250+
user: user._id,
251+
files: [
252+
{
253+
name: 'root',
254+
id: r,
255+
_id: r,
256+
children: [a, b, c],
257+
fileType: 'folder'
258+
},
259+
{
260+
name: 'sketch.js',
261+
content: '// Instance Mode: Instance Container, please check its index.html file',
262+
id: a,
263+
_id: a,
264+
fileType: 'file',
265+
children: []
266+
},
267+
{
268+
name: 'index.html',
269+
content: project.sketchContent,
270+
isSelectedFile: true,
271+
id: b,
272+
_id: b,
273+
fileType: 'file',
274+
children: []
275+
},
276+
{
277+
name: 'style.css',
278+
content: defaultCSS,
279+
id: c,
280+
_id: c,
281+
fileType: 'file',
282+
children: []
283+
}
284+
],
285+
_id: shortid.generate()
286+
});
287+
} else {
288+
newProject = new Project({
289+
name: project.projectName,
290+
user: user._id,
291+
files: [
292+
{
293+
name: 'root',
294+
id: r,
295+
_id: r,
296+
children: [a, b, c],
297+
fileType: 'folder'
298+
},
299+
{
300+
name: 'sketch.js',
301+
content: project.sketchContent,
302+
id: a,
303+
_id: a,
304+
isSelectedFile: true,
305+
fileType: 'file',
306+
children: []
307+
},
308+
{
309+
name: 'index.html',
310+
content: defaultHTML,
311+
id: b,
312+
_id: b,
313+
fileType: 'file',
314+
children: []
315+
},
316+
{
317+
name: 'style.css',
318+
content: defaultCSS,
319+
id: c,
320+
_id: c,
321+
fileType: 'file',
322+
children: []
323+
}
324+
],
325+
_id: shortid.generate()
326+
});
327+
}
335328

336-
await addAssetsToProject(assetsInProject, res, newProject);
329+
const assetsInProject = project.sketchContent.match(/assets\/[\w-]+\.[\w]*/g)
330+
|| project.sketchContent.match(/asset\/[\w-]*/g) || [];
337331

338-
newProject.save((saveErr, savedProject) => {
339-
if (saveErr) throw saveErr;
340-
console.log(`Created a new project in p5 user: ${savedProject.name}`);
341-
projectCallback();
342-
});
343-
}, (categoryErr) => {
344-
categoryCallback();
345-
});
346-
}, (examplesErr) => {
347-
process.exit();
348-
});
349-
});
350-
}).catch((err) => {
351-
throw err;
352-
});
332+
try {
333+
await addAssetsToProject(assetsInProject, res, newProject);
334+
const savedProject = await newProject.save();
335+
console.log(`Created a new project in p5 user: ${savedProject.name}`);
336+
} catch (error) {
337+
throw error;
338+
}
339+
}))));
340+
process.exit();
341+
} catch (error) {
342+
throw error;
343+
}
353344
}
354345

355-
function getp5User() {
346+
async function getp5User() {
356347
console.log('Getting p5 user');
357-
User.findOne({ username: 'p5' }, (err, user) => {
358-
if (err) throw err;
359-
348+
try {
349+
const user = await User.findOne({ username: 'p5' }).exec();
360350
let p5User = user;
361351
if (!p5User) {
362352
p5User = new User({
363353
username: 'p5',
364354
email: process.env.EXAMPLE_USER_EMAIL,
365355
password: process.env.EXAMPLE_USER_PASSWORD
366356
});
367-
p5User.save((saveErr) => {
368-
if (saveErr) throw saveErr;
369-
console.log(`Created a user p5 ${p5User}`);
370-
});
357+
await p5User.save();
358+
console.log(`Created a user p5 ${p5User}`);
371359
}
372-
373-
Project.find({ user: p5User._id }, (projectsErr, projects) => {
374-
// if there are already some sketches, delete them
375-
console.log('Deleting old projects...');
376-
projects.forEach((project) => {
377-
Project.remove({ _id: project._id }, (removeErr) => {
378-
if (removeErr) throw removeErr;
379-
});
380-
});
360+
const projects = await Project.find({ user: p5User._id }).exec();
361+
console.log('Deleting old projects...');
362+
projects.forEach(async (project) => {
363+
try {
364+
await Project.deleteOne({ _id: project._id });
365+
} catch (error) {
366+
throw error;
367+
}
381368
});
382-
383-
return getCategories()
384-
.then(getSketchesInCategories)
385-
.then(getSketchContent)
386-
.then(createProjectsInP5user);
387-
});
369+
const categories = await getCategories();
370+
const sketchesInCategories = await getSketchesInCategories(categories);
371+
const sketchContent = await getSketchContent(sketchesInCategories);
372+
const projectsInUser = createProjectsInP5user(sketchContent);
373+
return projectsInUser;
374+
} catch (error) {
375+
throw error;
376+
}
388377
}
389378

390379
getp5User();

0 commit comments

Comments
 (0)
Please sign in to comment.