Best way to return field types with list data for a JSON api?

60 views
Skip to first unread message

dust...@gmail.com

unread,
Jan 7, 2015, 2:27:55 PM1/7/15
to keyst...@googlegroups.com
I've been trying to figure out how to append or include the field types for client side validation in an Angular app that consumes Keystone as an API.

In a basic scenario I get a result like this:

{
"name": "ipad",
"quantity": "200",
"vendor": "apple",
"status": "available"
}

and what I need to get is:
 
something that tells me that "name" is a string
while "vendor" is a relationship 
and "status" is a Select with "x,y,z" options 
and that "quantity" is not editable or whatever, just as the model is configured for keystone for this data.  

This way I can setup client side forms that can post to the API with some level of automation using Angular directives etc.

My API looks something like this:

Products = keystone.list('Product')

exports
.list = (req, res) ->

 
Products.model.find().exec (err, products) ->

   
return res.apiError("database error", err)  if err

   
return res.apiError("not found")  unless products

    res
.apiResponse products


Let me know if you have any ideas!

Thanks,

Dustin

atlb...@gmail.com

unread,
Jan 7, 2015, 2:38:20 PM1/7/15
to keyst...@googlegroups.com
I'm on mobile so I can't give a good example but you should look at keystone.lists[key], with key being your list.

All the info you want should be available in that object.

dust...@gmail.com

unread,
Jan 7, 2015, 7:52:58 PM1/7/15
to keyst...@googlegroups.com
What a boss, to reply from your phone on this! Thanks,

Here is what I came up with and it works quite well, though I do with there was a less expensive way to do this.  At least with Coffeescript and Underscore it's only a few lines of code.

keystone = require('keystone')
Products = keystone.list('Product')
_ = require('underscore')


exports.list = (req, res) ->
  Products.model.find().lean().exec (err, products) ->
    return res.apiError("database error", err)  if err
    return res.apiError("not found")  unless products

    results = []

    for product, index in products

      joined_product = {}

      for field in _.keys(product)
        if keystone.lists['Product'].fields[field]
          joined_product[field] =
            value: product[field]
            type: keystone.lists['Product'].fields[field].type

      results.push joined_product

    res.apiResponse results



The nice thing is that now that I have that data I can auto generate a form based UI for my front end app similar to the Keystone admin itself, but with the ability to customize everything, including user level permissions.  Very powerful to have this.

If anyone comes up with a better method let me know!

Thanks,

Dustin


Reply all
Reply to author
Forward
0 new messages