postgrest-client
This library allows you to construct and execute postgrest requests with additional type safety.
Here's what Api.People might look like:
import Json.Decode exposing (..)
import Json.Encode as JE
import Postgrest.Client as P
-- Optional, but recommended to have a type that
-- represents your primary key.
type PersonID
= PersonID Int
-- And a way to unwrap it...
personID : PersonID -> Int
personID (PersonID id) =
id
-- Define the record you would fetch back from the server.
type alias Person =
{ id : PersonID
, name : String
}
-- Define a submission record, without the primary key.
type alias PersonSubmission =
{ name : String
}
-- Decoders are written using Json.Decode
decodeUnit : Decoder Person
decodeUnit =
map2 Person
(field "id" <| map PersonID int)
(field "name" string)
-- Encoders are written using Json.Encode
encode : PersonSubmission -> JE.Value
encode person =
JE.object
[ ( "name", JE.string person.name )
]
-- Tell Postgrest.Client the column name of your primary key and
-- how to convert it into a parameter.
primaryKey : P.PrimaryKey PersonID
primaryKey =
P.primaryKey ( "id", P.int << personID )
-- Tell Postgrest.Client the URL of the postgrest endpoint and how
-- to decode an individual record from it. Postgrest will combine
-- the decoder with a list decoder automatically when necessary.
endpoint : P.Endpoint Person
endpoint =
P.endpoint "/people" decodeUnit
-- Fetch many records. If you want to specify parameters use `setParams`
getMany : P.Request (List Person)
getMany =
P.getMany endpoint
-- Delete by primary key. This is a convenience function that reduces
-- the likelihood that you delete more than one record by specifying incorrect
-- parameters.
delete : PersonID -> P.Request PersonID
delete =
P.deleteByPrimaryKey endpoint primaryKey
-- Create a record.
post : PersonSubmission -> P.Request Person
post =
P.postOne endpoint << encode
Here's how you could use it:
import Api.People as People
import Postgrest.Client as P
jwt : P.JWT
jwt =
P.jwt "abcdefghijklmnopqrstuvwxyz1234"
type Msg
= PersonCreated (Result P.Error Person)
| PeopleLoaded (Result P.Error (List Person))
| PersonDeleted (Result P.Error PersonID)
toCmd =
P.toCmd jwt
cmdExamples =
[ People.post
{ name = "Yasujirō Ozu"
}
|> P.toCmd jwt PersonCreated
, People.getMany
[ P.order [ P.asc "name" ], P.limit 10 ]
|> toCmd PeopleLoaded
, Person.delete personID
|> toCmd PersonDeleted
]
Request Construction and Modification
Think of an Endpoint as a combination between a base url like
/schoolsand an elm/jsonDecoder. The endpoint can be passed to other functions in this library, sometimes along with PrimaryKey to make constructing certain types of requests easier.