diff --git a/models/books_add.go b/models/books_add.go index 09eb1c3..081911c 100644 --- a/models/books_add.go +++ b/models/books_add.go @@ -1,14 +1,92 @@ package models -func AddBook(book Book) (newBook Book, err error){ +/** +::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 wirdebenfalls überprüft, ob sie bereits existieren, wenn dem nicht so ist werden +sie in die Datenbank eingetragen und mit dem Buch verknüpft. + + */ + +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 book, err -} \ No newline at end of file + return newBook, err +}