|
| 1 | +// app/controllers/admin/seeder.js |
| 2 | +import Ember from 'ember'; |
| 3 | +import Faker from 'faker'; |
| 4 | + |
| 5 | +export default Ember.Controller.extend({ |
| 6 | + |
| 7 | + libraries: [], |
| 8 | + books: [], |
| 9 | + authors: [], |
| 10 | + |
| 11 | + actions: { |
| 12 | + |
| 13 | + generateLibraries() { |
| 14 | + const counter = parseInt(this.get('librariesCounter')); |
| 15 | + |
| 16 | + for (let i = 0; i < counter; i++) { |
| 17 | + this.store.createRecord('library').randomize().save().then(() => { |
| 18 | + if (i === counter-1) { |
| 19 | + this.set('librariesCounter', 0); |
| 20 | + this.set('libDone', true); |
| 21 | + } |
| 22 | + }); |
| 23 | + } |
| 24 | + }, |
| 25 | + |
| 26 | + deleteLibraries() { |
| 27 | + this._destroyAll(this.get('libraries')); |
| 28 | + |
| 29 | + this.set('libDelDone', true); |
| 30 | + }, |
| 31 | + |
| 32 | + generateBooksAndAuthors() { |
| 33 | + const counter = parseInt(this.get('authorCounter')); |
| 34 | + |
| 35 | + for (let i = 0; i < counter; i++) { |
| 36 | + let newAuthor = this.store.createRecord('author'); |
| 37 | + newAuthor.randomize() |
| 38 | + .save().then(() => { |
| 39 | + if (i === counter-1) { |
| 40 | + this.set('authorCounter', 0); |
| 41 | + this.set('authDone', true); |
| 42 | + } |
| 43 | + } |
| 44 | + ); |
| 45 | + |
| 46 | + this._generateSomeBooks(newAuthor); |
| 47 | + } |
| 48 | + }, |
| 49 | + |
| 50 | + deleteBooksAndAuthors() { |
| 51 | + this._destroyAll(this.get('books')); |
| 52 | + this._destroyAll(this.get('authors')); |
| 53 | + |
| 54 | + this.set('authDelDone', true); |
| 55 | + } |
| 56 | + }, |
| 57 | + |
| 58 | + // Private methods |
| 59 | + |
| 60 | + _generateSomeBooks(author) { |
| 61 | + const bookCounter = Faker.random.number(10); |
| 62 | + |
| 63 | + for (let j = 0; j < bookCounter; j++) { |
| 64 | + const library = this._selectRandomLibrary(); |
| 65 | + this.store.createRecord('book') |
| 66 | + .randomize(author, library) |
| 67 | + .save(); |
| 68 | + author.save(); |
| 69 | + library.save(); |
| 70 | + } |
| 71 | + }, |
| 72 | + |
| 73 | + _selectRandomLibrary() { |
| 74 | + const libraries = this.get('libraries'); |
| 75 | + const librariesCounter = libraries.get('length'); |
| 76 | + |
| 77 | + // Create a new array from IDs |
| 78 | + const libraryIds = libraries.map((lib) => {return lib.get('id');}); |
| 79 | + const randomNumber = Faker.random.number(librariesCounter-1); |
| 80 | + |
| 81 | + const randomLibrary = libraries.findBy('id', libraryIds[randomNumber]); |
| 82 | + return randomLibrary; |
| 83 | + }, |
| 84 | + |
| 85 | + _destroyAll(records) { |
| 86 | + records.forEach((item) => { |
| 87 | + item.destroyRecord(); |
| 88 | + }); |
| 89 | + } |
| 90 | + |
| 91 | +}); |
0 commit comments