open source / oauth4s / json codecs
JSON codecs
core reads and writes JSON through a JsonCodec. The built-in one has no dependencies and is the default. Importing
the instances of a library replaces it, and lets that library's decoders read user info, claims and resources:
| Module | Import |
|---|---|
oauth4s-circe |
oauth4s.json.circe.CirceInstances.given |
oauth4s-zio-json |
oauth4s.json.zio.ZioJsonInstances.given |
oauth4s-jsoniter |
oauth4s.json.jsoniter.JsoniterInstances.given |
scala
final case class Me(sub: String, locale: Option[String]) derives Decoder
def me(oidc: OidcClient[IO], token: AccessToken): IO[Either[JsonError, Me]] =
oidc.userInfo(token).map(_.decode[Me]) // with circe's Decoder[Me]
def claims(tokens: OidcTokens): Either[JsonError, Me] =
tokens.idToken.claims.decode[Me]
def resource(client: OAuthClient[IO], token: AccessToken): IO[Either[JsonError, Me]] =
client.resource(Endpoint("https://api.example.com/me"), token).map(_.as[Me])Each module also gives the library codecs for TokenResponse, so a token is stored the way the rest of your data is:
scala
def stored(token: TokenResponse): String = token.asJson.noSpaces // access_token, refresh_token, …, and when it was issued
def restored(text: String): Either[io.circe.Error, TokenResponse] = decode[TokenResponse](text)The stored form keeps issued_at, so a restored token still knows when it expires.
A decoder does not need a library:
scala
final case class Plan(name: String, seats: Long)
given JsonDecoder[Plan] = JsonDecoder.instance { json =>
for
name <- json.string("name").toRight(JsonError.MissingField("name"))
seats <- json.long("seats").toRight(JsonError.InvalidField("seats", "is not a whole number"))
yield Plan(name, seats)
}
def plan(json: Json): Either[JsonError, Plan] = json.as[Plan]All four codecs pass the same suite: the same tree for the same text, and a refusal of trailing commas, unterminated arrays, empty input and anything after the document.
built from README.md at v0.1.1
edit this page on GitHub