ponzu-cms / ponzu

Headless CMS with automatic JSON API. Featuring auto-HTTPS from Let's Encrypt, HTTP/2 Server Push, and flexible server framework written in Go.
https://docs.ponzu-cms.org
BSD 3-Clause "New" or "Revised" License
5.68k stars 387 forks source link

How to get a list of books for one author #296

Closed xu4wang closed 4 years ago

xu4wang commented 5 years ago

Hello Ponzu User

I'm reading the Author and Books demo, The Author is a type in Ponzu and Book is another Type, There is a reference to Author in type Book.

If I want to list all the books from one author via HTTP API call, How should I implement in Ponzu?

Thanks,Austin

nilslice commented 5 years ago

@xu4wang - hello! you could add full-text search by implementing the db.Searchable interface, and doing a search for the reference URL.

To implement the interface, simply add a IndexContent() bool method that returns true to your Book type.

To search the database, use the search HTTP endpoint:

GET /api/search?type=Book&q=author:/api/content?type=Post&id=1

You may need to alter the query a bit, but that is the idea.

Alternatively, can also do your own lookups directly on the database. The db.Query function takes a Type name and returns a a list of the JSON encoded values, which you could iterate through, decode, and check for the Author ID to filter the results. For example:

books, count := db.Query("Book", db.QueryOptions{})
fmt.Println("total books found:", count)

var authorsBooks []content.Book{}
for _, book := range books {
    // unmarshal JSON `book`
    // check if book.Author == /api/content?type=Author&id=$YOUR_AUTHOR_ID
    // if true, append unmarshalled book to `authorsBooks`
}

return authorsBooks

This function would need to be registered as a new HTTP route, which you can do on the default http.ServeMux, even directly within your content package book.go file:

// content/book.go
func init() {
    http.HandleFunc("/api/booksByAuthor", yourFilterFunc)
}

Let me know if this helps, or if you have any other issues trying to get your desired results. Also, if you have ideas how to improve Ponzu to make this easier, please let me know 👍 Thanks!

olliephillips commented 4 years ago

Closing this one. Feel free to reopen if needed.