Created
October 17, 2014 21:32
-
-
Save dysinger/c240e5cb706513bd8175 to your computer and use it in GitHub Desktop.
using camelCase for mapping from JSON with Purescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| {- | |
| Author | Tim Dysinger <tim@dysinger.net> | |
| Copyright | WTFPL 2.0 http://www.gnu.org/licenses/license-list.html#WTFPL | |
| -} | |
| module Main where | |
| import Control.Monad.Eff | |
| import Data.Array | |
| import Data.Foreign | |
| import Debug.Trace | |
| {- GOAL: Take an example Amazon API response & use it in PS. Amazon | |
| uses "PascalCase" in it's Webservice API. This breaks Purescript's | |
| mapping to record attributes. Purescript uses PascalCase for data | |
| types and camelCase for functions & attributes. -} | |
| foreign import data AWS :: ! | |
| foreign import amazonWebServiceRegions | |
| """ | |
| function amazonWebServiceRegions() { | |
| return { | |
| "Regions": [ | |
| { | |
| "Endpoint": "ec2.eu-west-1.amazonaws.com", | |
| "RegionName": "eu-west-1" | |
| }, | |
| { | |
| "Endpoint": "ec2.sa-east-1.amazonaws.com", | |
| "RegionName": "sa-east-1" | |
| }, | |
| { | |
| "Endpoint": "ec2.us-east-1.amazonaws.com", | |
| "RegionName": "us-east-1" | |
| }, | |
| { | |
| "Endpoint": "ec2.ap-northeast-1.amazonaws.com", | |
| "RegionName": "ap-northeast-1" | |
| }, | |
| { | |
| "Endpoint": "ec2.us-west-2.amazonaws.com", | |
| "RegionName": "us-west-2" | |
| }, | |
| { | |
| "Endpoint": "ec2.us-west-1.amazonaws.com", | |
| "RegionName": "us-west-1" | |
| }, | |
| { | |
| "Endpoint": "ec2.ap-southeast-1.amazonaws.com", | |
| "RegionName": "ap-southeast-1" | |
| }, | |
| { | |
| "Endpoint": "ec2.ap-southeast-2.amazonaws.com", | |
| "RegionName": "ap-southeast-2" | |
| } | |
| ] | |
| } | |
| } | |
| """ | |
| :: forall e. Eff (aws :: AWS | e) Foreign | |
| foreign import camelCase | |
| """ | |
| var us = require('underscore'); | |
| var cc = require('change-case'); | |
| function camelCase(obj) { | |
| if ( us.isArray(obj) ) { | |
| return us.map(obj, camelCase); | |
| } else if ( us.isObject(obj) ) { | |
| return us.reduce(us.pairs(obj), function(m, p) { | |
| m[cc.camelCase(p[0])] = camelCase(p[1]); | |
| return m; | |
| }, {}); | |
| } else { | |
| return obj; | |
| } | |
| } | |
| """ | |
| :: Foreign -> Foreign | |
| main = do | |
| rs <- amazonWebServiceRegions >>= return <<< unsafeFromForeign <<< camelCase | |
| print $ map (\r -> r.regionName :: String) rs.regions | |
| -- prints ["eu-west-1","sa-east-1","us-east-1","ap-northeast-1","us-west-2","us-west-1","ap-southeast-1","ap-southeast-2"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment