Skip to content

Commit 8fc9f8d

Browse files
authored
Merge pull request #4 from eug-vs/populateDb
Populate db script
2 parents 40b804f + 56c9c33 commit 8fc9f8d

File tree

3 files changed

+66
-2
lines changed

3 files changed

+66
-2
lines changed

models/polls/poll.schema.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { Document, Schema, Types } from 'mongoose';
22
import { User } from '../users/user.schema'
33

4-
interface ImageData {
4+
export interface ImageData {
55
url: string;
66
votes: number;
77
}

package-lock.json

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

populateDb.ts

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import mongoose from 'mongoose';
2+
import bluebird from 'bluebird';
3+
import _ from 'lodash';
4+
import app from './app';
5+
import { UserSchema } from './models/users/user.schema';
6+
import { PollSchema, ImageData } from './models/polls/poll.schema';
7+
8+
mongoose.connect('mongodb://localhost:27017/which', { useNewUrlParser: true });
9+
10+
const POLLS_AMOUNT = 20;
11+
12+
const imageUrls: string[] = [
13+
// eslint-disable max-len
14+
'https://cdn.psychologytoday.com/sites/default/files/field_blog_entry_images/2019-06/pexels-photo-556667.jpeg',
15+
'https://images.pexels.com/photos/556666/pexels-photo-556666.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500',
16+
'https://i.pinimg.com/originals/50/91/3e/50913eeb04768a5b1fa9985c16704d96.jpg',
17+
'https://grazia.wwmindia.com/photogallery/2017/apr/1_1491461089.jpg'
18+
];
19+
20+
const names: string[] = [
21+
'Emma',
22+
'Elise',
23+
'Jack',
24+
'Oliver',
25+
'Jamie',
26+
'Adam',
27+
'Jordan',
28+
'William'
29+
];
30+
31+
const generateImageData = (): ImageData => ({
32+
url: _.sample(imageUrls) || '',
33+
votes: Math.floor(Math.random() * 101)
34+
});
35+
36+
const createPoll = (authorId: string): Promise<PollSchema> => {
37+
return app.service('polls').create({
38+
contents: {
39+
left: generateImageData(),
40+
right: generateImageData(),
41+
},
42+
authorId
43+
});
44+
};
45+
46+
const createUser = (name: string): Promise<UserSchema> => {
47+
return app.service('users').create({
48+
avatarUrl: _.sample(imageUrls) || '',
49+
name
50+
});
51+
};
52+
53+
54+
const populate = async () => {
55+
const users = await bluebird.map(names, name => createUser(name));
56+
57+
for (let i = 0; i < POLLS_AMOUNT; i++) {
58+
const sampleUser = _.sample(users);
59+
await createPoll(sampleUser?._id);
60+
};
61+
};
62+
63+
populate().finally(mongoose.disconnect);
64+

0 commit comments

Comments
 (0)