Skip to content

Commit c0e0fb9

Browse files
author
Railway Agent
committed
Add database initialization script
1 parent 304ce8b commit c0e0fb9

1 file changed

Lines changed: 202 additions & 0 deletions

File tree

scripts/init-db.js

Lines changed: 202 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,202 @@
1+
#!/usr/bin/env node
2+
3+
/**
4+
* Script para inicializar o banco de dados com dados de exemplo
5+
* Uso: node scripts/init-db.js
6+
*/
7+
8+
const mongoose = require("mongoose");
9+
const Book = require("../models/book");
10+
const Author = require("../models/author");
11+
const Genre = require("../models/genre");
12+
const BookInstance = require("../models/bookinstance");
13+
14+
const mongoDB = process.env.MONGODB_URI || "mongodb://localhost:27017/local_library";
15+
16+
const genres = [];
17+
const authors = [];
18+
const books = [];
19+
const bookinstances = [];
20+
21+
main().catch((err) => {
22+
console.error("Erro ao inicializar banco de dados:", err);
23+
process.exit(1);
24+
});
25+
26+
async function main() {
27+
console.log("Conectando ao MongoDB...");
28+
await mongoose.connect(mongoDB);
29+
console.log("Conectado com sucesso!");
30+
31+
// Limpar dados existentes (opcional)
32+
console.log("Limpando dados existentes...");
33+
await Promise.all([
34+
Genre.deleteMany({}),
35+
Author.deleteMany({}),
36+
Book.deleteMany({}),
37+
BookInstance.deleteMany({}),
38+
]);
39+
40+
console.log("Criando gêneros...");
41+
await createGenres();
42+
console.log("Criando autores...");
43+
await createAuthors();
44+
console.log("Criando livros...");
45+
await createBooks();
46+
console.log("Criando instâncias de livros...");
47+
await createBookInstances();
48+
49+
console.log("Banco de dados inicializado com sucesso!");
50+
await mongoose.connection.close();
51+
process.exit(0);
52+
}
53+
54+
async function genreCreate(index, name) {
55+
const genre = new Genre({ name: name });
56+
await genre.save();
57+
genres[index] = genre;
58+
console.log(` ✓ Gênero adicionado: ${name}`);
59+
}
60+
61+
async function authorCreate(index, first_name, family_name, d_birth, d_death) {
62+
const authordetail = { first_name: first_name, family_name: family_name };
63+
if (d_birth != false) authordetail.date_of_birth = d_birth;
64+
if (d_death != false) authordetail.date_of_death = d_death;
65+
66+
const author = new Author(authordetail);
67+
await author.save();
68+
authors[index] = author;
69+
console.log(` ✓ Autor adicionado: ${first_name} ${family_name}`);
70+
}
71+
72+
async function bookCreate(index, title, summary, isbn, author, genre) {
73+
const bookdetail = {
74+
title,
75+
summary,
76+
author,
77+
isbn,
78+
};
79+
if (genre != false) bookdetail.genre = genre;
80+
81+
const book = new Book(bookdetail);
82+
await book.save();
83+
books[index] = book;
84+
console.log(` ✓ Livro adicionado: ${title}`);
85+
}
86+
87+
async function bookInstanceCreate(index, book, imprint, due_back, status) {
88+
const bookinstancedetail = {
89+
book,
90+
imprint,
91+
};
92+
if (due_back != false) bookinstancedetail.due_back = due_back;
93+
if (status != false) bookinstancedetail.status = status;
94+
95+
const bookinstance = new BookInstance(bookinstancedetail);
96+
await bookinstance.save();
97+
bookinstances[index] = bookinstance;
98+
console.log(` ✓ Instância de livro adicionada: ${imprint}`);
99+
}
100+
101+
async function createGenres() {
102+
await Promise.all([
103+
genreCreate(0, "Fantasy"),
104+
genreCreate(1, "Science Fiction"),
105+
genreCreate(2, "French Poetry"),
106+
]);
107+
}
108+
109+
async function createAuthors() {
110+
await Promise.all([
111+
authorCreate(0, "Patrick", "Rothfuss", "1973-06-06", false),
112+
authorCreate(1, "Ben", "Bova", "1932-11-08", false),
113+
authorCreate(2, "Isaac", "Asimov", "1920-01-02", "1992-04-06"),
114+
authorCreate(3, "Bob", "Billings", false, false),
115+
authorCreate(4, "Jim", "Jones", "1971-12-16", false),
116+
]);
117+
}
118+
119+
async function createBooks() {
120+
await Promise.all([
121+
bookCreate(
122+
0,
123+
"The Name of the Wind (The Kingkiller Chronicle, #1)",
124+
"I have stolen princesses back from sleeping barrow kings. I burned down the town of Trebon. I have spent the night with Felurian and left with both my sanity and my life. I was expelled from the University at a younger age than most people are allowed in. I tread paths by moonlight that others fear to speak of during day. I have talked to Gods, loved women, and written songs that make the minstrels weep.",
125+
"9781473211896",
126+
authors[0],
127+
[genres[0]]
128+
),
129+
bookCreate(
130+
1,
131+
"The Wise Man's Fear (The Kingkiller Chronicle, #2)",
132+
"Picking up the tale of Kvothe Kingkiller once again, we follow him into exile, into political intrigue, courtship, adventure, love and magic... and further along the path that has turned Kvothe, the mightiest magician of his age, a legend in his own time, into Kote, the unassuming pub landlord.",
133+
"9788401352836",
134+
authors[0],
135+
[genres[0]]
136+
),
137+
bookCreate(
138+
2,
139+
"The Slow Regard of Silent Things (King Killer Chronicle)",
140+
"The Slow Regard of Silent Things is a fantasy novella by Patrick Rothfuss, the author of The Name of the Wind and The Wise Man's Fear.",
141+
"9780575095151",
142+
authors[0],
143+
[genres[0]]
144+
),
145+
bookCreate(
146+
3,
147+
"Apes and Angels",
148+
"Humankind headed outward to conquer the planets, then swung around and conquered them back... Except for Venus, our planet of failure, to which organillionaire Cyril Oakes sends a single ship.",
149+
"9780671578626",
150+
authors[1],
151+
[genres[1]]
152+
),
153+
bookCreate(
154+
4,
155+
"Death Wave",
156+
"In Ben Bova's previous novel Star Quest, Jordan Kell discovered that the an alien race was attempting to enslave all of humanity, and a dead alien came with a warning. Now the second wave of their invasion fleet is on its way, and humanity has no way of stopping it.",
157+
"9780671578626",
158+
authors[1],
159+
[genres[1]]
160+
),
161+
bookCreate(
162+
5,
163+
"Foundation",
164+
"The Foundation series is a science fiction series by Isaac Asimov. It is set in a distant future of the Galactic Empire and the parallel story of the Foundation.",
165+
"9780553293357",
166+
authors[2],
167+
[genres[1]]
168+
),
169+
bookCreate(
170+
6,
171+
"Foundation and Empire",
172+
"Foundation and Empire is the second novel in Isaac Asimov's Foundation series. It is set in a distant future of the Galactic Empire and the parallel story of the Foundation.",
173+
"9780553293364",
174+
authors[2],
175+
[genres[1]]
176+
),
177+
bookCreate(
178+
7,
179+
"Second Foundation",
180+
"Second Foundation is the third novel in Isaac Asimov's Foundation series. It is set in a distant future of the Galactic Empire and the parallel story of the Foundation.",
181+
"9780553293371",
182+
authors[2],
183+
[genres[1]]
184+
),
185+
]);
186+
}
187+
188+
async function createBookInstances() {
189+
await Promise.all([
190+
bookInstanceCreate(0, books[0], "London Gollancz, 2014.", false, "Available"),
191+
bookInstanceCreate(1, books[1], "Gollancz, 2011.", false, "Loaned"),
192+
bookInstanceCreate(2, books[2], "Gollancz, 2015.", false, "Loaned"),
193+
bookInstanceCreate(3, books[3], "New York Tom Doherty Associates, 2016.", false, "Available"),
194+
bookInstanceCreate(4, books[4], "New York Tom Doherty Associates, 2015.", false, "Available"),
195+
bookInstanceCreate(5, books[4], "New York Tom Doherty Associates, 2015.", false, "Maintenance"),
196+
bookInstanceCreate(6, books[4], "New York Tom Doherty Associates, 2015.", false, "Loaned"),
197+
bookInstanceCreate(7, books[0], "Imprint XXX2", "2025-12-30", "Loaned"),
198+
bookInstanceCreate(8, books[1], "Imprint XXX 3", "2025-12-30", "Available"),
199+
bookInstanceCreate(9, books[3], "Imprint XXX 4", false, "Available"),
200+
]);
201+
}
202+

0 commit comments

Comments
 (0)