Created
September 30, 2021 21:28
-
-
Save FeMaffezzolli/3b47371a09ccafe59e7bfea9be30d850 to your computer and use it in GitHub Desktop.
Adonis.js Seed Example (without factory)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import faker from 'faker' | |
import { sample } from 'lodash' | |
import { DateTime } from 'luxon' | |
import BaseSeeder from '@ioc:Adonis/Lucid/Seeder' | |
import User from 'App/Models/User' | |
import Transaction from 'App/Models/Transaction' | |
import TransactionCategory from 'App/Models/TransactionCategory' | |
import TransactionSubCategory from 'App/Models/TransactionSubCategory' | |
import TransactionType from 'App/Models/TransactionType' | |
export default class UserSeeder extends BaseSeeder { | |
protected async getRandomModelId(model) { | |
const records = await model.all() | |
const randomId = sample(records) | |
if (!randomId) throw new Error('Missing transaction category.') | |
return randomId.id | |
} | |
public async run() { | |
const user = await User.firstOrCreate({ | |
email: '[email protected]', | |
password: 'topsecret', | |
name: 'Regular User', | |
isAdmin: false, | |
}) | |
const transactionsVector = await Promise.all( | |
Array.from({ length: 350 }).map(async () => ({ | |
userId: user.id, | |
date: DateTime.fromJSDate(faker.date.recent()), | |
amount: Number(faker.finance.amount(80, 8000, 2)), | |
transactionTypeId: await this.getRandomModelId(TransactionType), | |
transactionCategoryId: await this.getRandomModelId(TransactionCategory), | |
transactionSubCategoryId: await this.getRandomModelId(TransactionSubCategory), | |
})) | |
) | |
await Transaction.createMany(transactionsVector) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment