Library/models/books_add.go

94 lines
2.3 KiB
Go

package models
/**
::USAGE::
Erwatet ein Struct mit einem Buch.
Wenn dieses Struct einen Publisher in Book.Publisher enthält und dieser existiert, wird diese
ID verwendet. Wenn die ID nicht existiert oder 0 ist, wird geguckt, ob der Publisher unter
Book.PublisherFull bereits existtiert (über die ID), ist das nicht der Fall, wird er in
die Datenbank eingetragen und mit dem Buch verknüpft.
Bei den Autoren wird ebenfalls überprüft, ob sie bereits existieren, wenn dem nicht so ist werden
sie in die Datenbank eingetragen und mit dem Buch verknüpft.
*/
// AddBook adds a new book, it takes a book struct with author and publisher. Inserts them if they don't already exist
func AddBook(book Book) (newBook Book, err error) {
// Take Publisher, check if it exists. If not, insert it
exists := false
publisherid := book.Publisher
if publisherid == 0 {
if book.PublisherFull.ID != 0 {
publisherid = book.PublisherFull.ID
}
}
_, exists, err = GetPublisherByID(book.Publisher)
if err != nil {
return Book{}, err
}
if !exists {
bookToBeInserted := new(Publisher)
bookToBeInserted.Name = book.PublisherFull.Name
_, err = x.Insert(bookToBeInserted)
if err != nil {
return Book{}, err
}
book.Publisher = bookToBeInserted.ID
}
// Insert the Book
_, err = x.Insert(&book)
if err != nil {
return Book{}, err
}
// Take the authors, look if they exist, if they don't create them
authorBookRelation := make([]AuthorBook, 0)
for _, author := range book.Authors {
_, exists, err := GetAuthorByID(author.ID)
if err != nil {
return Book{}, err
}
if !exists {
// We have to insert authors on this inperformant way, because we need the ne ids afterwards
authorToBeInserted := new(Author)
authorToBeInserted.Forename = author.Forename
authorToBeInserted.Lastname = author.Lastname
_, err := x.Insert(authorToBeInserted)
if err != nil {
return Book{}, err
}
author.ID = authorToBeInserted.ID
}
// Prepare new author Relateion
authorBookRelation = append(authorBookRelation, AuthorBook{BookID: book.ID, AuthorID: author.ID})
}
// Insert the connection between the author and the book
_, err = x.Insert(&authorBookRelation)
if err != nil {
return Book{}, err
}
// Get the newly inserted book
newBook, _, err = GetBookById(book.ID)
return newBook, err
}