-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathseed.js
234 lines (183 loc) · 5.77 KB
/
seed.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
require ('dotenv/config');
const fs = require('fs');
const request = require ('request');
const db = require ('./src/config/db');
const faker = require('faker');
const { hash } = require ('bcryptjs');
const User = require ('./src/app/models/User');
const Chef = require ('./src/app/models/Chef');
const File = require ('./src/app/models/File');
const Recipe = require ('./src/app/models/Recipe');
let usersIds = [];
let chefsIds = [];
let recipesIds = [];
const totalUsers = 5;
const totalChefs = 12;
const totalRecipes = 30;
/////////////////////// COMPLEMENTARY FUNCTIONS ///////////////////////
function message(text, error){
if(error){
console.log (`Something went wrong during the ${text}`);
} else{
console.log (text);
}
}
function randNumber(min, max){
return Math.floor(Math.random() * (max - min + 1) ) + min;
}
///////////////////////// AUXILIARY FUNCTIONS /////////////////////////
function textList(size){
let textArray = [];
for (let i=0; i<size; i++){
textArray.push(faker.lorem.sentence(randNumber(2,7)));
}
return textArray;
}
async function downloadImage(type, number){
try {
const url = `http://placehold.it/500?text=${type}_${number}`;
const path = `./public/img/${type}s_images/${type}_${number}.png`
request(url).pipe(fs.createWriteStream(path));
return `public/img/${type}s_images/${type}_${number}.png`;
} catch (err) {
console.error(err);
message(`${type} file creation process`, true);
}
}
async function createAvatar(id){
const path = await downloadImage('chef', id);
const fileId = await File.create({
name: `Chef_${id}_avatar`,
path
});
await Chef.linkFile(id, fileId);
return;
}
async function createRecipeImages (id, total){
for (let i=0; i<total; i++){
const path = await downloadImage('recipe', `${id}_${i}`);
const fileId = await File.create({
name: `Recipe_${id}_image_${i+1}`,
path
});
await Recipe.linkFile(id, fileId);
}
return;
}
//////////////////////// RESET/ERASE FUNCTIONS ///////////////////////
async function resetfiles(folder){
try {
const folderPath = `./public/img/${folder}_images`;
const files = fs.readdirSync(folderPath);
files.map(file => fs.unlinkSync(`${folderPath}/${file}`));
message(`All ${folder} files were deleted`);
return;
} catch (err) {
console.error(err);
message(`Deleting process for ${folder}`, true);
}
}
async function resetTables(){
try {
const query = `
DELETE FROM chef_files;
DELETE FROM recipe_files;
DELETE FROM files;
DELETE FROM recipes;
DELETE FROM chefs;
DELETE FROM session;
DELETE FROM users;
ALTER SEQUENCE chef_files_id_seq RESTART WITH 1;
ALTER SEQUENCE chefs_id_seq RESTART WITH 1;
ALTER SEQUENCE files_id_seq RESTART WITH 1;
ALTER SEQUENCE recipe_files_id_seq RESTART WITH 1;
ALTER SEQUENCE recipes_id_seq RESTART WITH 1;
ALTER SEQUENCE users_id_seq RESTART WITH 1;
INSERT INTO chefs(name) VALUES ('Foodfy');
INSERT INTO files(name, path) VALUES ('Foodfy_avatar', 'public/img/foodfy-avatar.png');
INSERT INTO chef_files(chef_id, file_id) VALUES ('1', '1');
`;
await db.query(query);
message (`All tables were cleaned`)
return;
} catch (err) {
console.error(err);
message(`process of reseting the tables`);
}
}
//////////////////////// CREATION FUNCTIONS /////////////////////////
async function createUsers(){
try {
const users = [];
const password = await hash('1234', 8);
while (users.length < totalUsers){
const firstName = faker.name.firstName();
users.push({
name: `${firstName} ${faker.name.lastName()}`,
email: `${firstName.toLocaleLowerCase()}${randNumber(1,9)}@mail.com`,
password,
is_admin: (users.length==0) ? true : faker.random.boolean(),
is_verified: (users.length==0) ? true : faker.random.boolean()
});
}
const usersPromise = users.map(user => User.create(user));
usersIds = await Promise.all(usersPromise);
message('All Users were created')
return;
} catch (err) {
console.error(err);
message('User creation process', true)
}
}
async function createChefs(){
try {
const chefs = [];
while (chefs.length < totalChefs){
const name = `${faker.name.firstName()} ${faker.name.lastName()}`;
chefs.push({
name
});
}
const chefsPromise = chefs.map(chef => Chef.create(chef));
chefsIds = await Promise.all(chefsPromise);
message('All Chefs were created');
const avatarPromise = chefsIds.map(id => createAvatar(id));
await Promise.all(avatarPromise);
return;
} catch (err) {
console.error(err);
message('Chefs creation process');
}
}
async function createRecipes(){
const recipes = [];
while (recipes.length < totalRecipes){
recipes.push({
chef_id: chefsIds[randNumber(1, totalChefs-1)],
user_id: usersIds[randNumber(0, totalUsers-1)],
title: faker.commerce.productName(),
ingredients: textList(randNumber(2,6)),
preparation: textList(randNumber(2,8)),
information: faker.lorem.paragraphs(randNumber(1,5))
});
}
const recipesPromise = recipes.map(recipe => Recipe.create(recipe));
recipesIds = await Promise.all(recipesPromise);
const recipeImagesPromise = recipesIds.map(id => createRecipeImages(id, randNumber(2,5)));
await Promise.all(recipeImagesPromise);
return;
}
///////////////////////// EXPORTABLE FUNCTIONS /////////////////////////
async function init() {
await resetfiles('chefs');
await resetfiles('recipes');
await resetTables();
await createUsers();
await createChefs();
await createRecipes();
return;
}
// if (process.argv.includes('freshStart')) {
// freshStart();
// }
init();