Skip to content

Commit

Permalink
Merge pull request #53 from tarao/js-interop
Browse files Browse the repository at this point in the history
Support conversion from/to native JS objects
  • Loading branch information
tarao authored Dec 19, 2023
2 parents 8f550b1 + f8a95e7 commit 440bcb8
Show file tree
Hide file tree
Showing 12 changed files with 922 additions and 2 deletions.
5 changes: 5 additions & 0 deletions build.sbt
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,11 @@ lazy val core = crossProject(JVMPlatform, JSPlatform, NativePlatform)
"org.scalatest" %%% "scalatest" % scalaTestVersion % Test,
),
)
.jsSettings(
libraryDependencies ++= Seq(
"org.getshaka" %%% "native-converter" % "0.9.0",
),
)

lazy val circe = crossProject(JVMPlatform, JSPlatform, NativePlatform)
.crossType(CrossType.Pure)
Expand Down
9 changes: 9 additions & 0 deletions docs/conversions.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ detail.

[circe]: https://circe.github.io/circe/

In Scala.js, `fromJSON` and `toJSON` methods are available. See [Converting a Record from
/ to a JSON string] for the detail.

From / To JavaScript Objects
----------------------------

In Scala.js, `fromJS` and `toJS` methods are available. See [Converting a Record from / to
a Native JavaScript Object] for the detail.

Upcast
------

Expand Down
1 change: 1 addition & 0 deletions docs/directory.conf
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ laika.navigationOrder = [
conversions.md
methods.md
pattern-matching.md
scalajs.md
performance.md
faq.md
integrations
Expand Down
91 changes: 91 additions & 0 deletions docs/scalajs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
Scala.js Support
================

Basically, record4s works fine in Scala.js because it is mostly written in pure Scala
code. Sometimes you may wish to use records with native JavaScript code and that will
require some additional mechanism.

Converting a Record from / to a Native JavaScript Object
--------------------------------------------------------

You can use `fromJS` and `toJS` to convert a record from/to a native JS object.

```scala
import com.github.tarao.record4s.%
import scala.scalajs.js

val obj: js.Any = js.Dynamic.literal(name = "tarao", age = 3)

// convert obj to a record
val r = Record.fromJS[% { val name: String; val age: Int }](obj)
// val r: %{val name: String; val age: Int} = %(name = tarao, age = 3)

// convert the record again to a JS object
val j = r.toJS
// val j: js.Any = [object Object]
```

Converting a Record from / to a JSON string
-------------------------------------------

Methods `fromJSON` and `toJSON` convert a record from/to JSON string internally using
`JSON.parse` and `JSON.stringify`.

```scala
import com.github.tarao.record4s.%

val json = """{"name":"tarao","age":3}"""

// convert a JSON string to a record
val r = Record.fromJSON[% { val name: String; val age: Int }](json)
// val r: %{val name: String; val age: Int} = %(name = tarao, age = 3)

// convert the record again to a JSON string
val j = r.toJSON
// val j: String = {"name":"tarao","age":3}
```

Converting Nested Types
-----------------------

All these conversions described above support nested types.

```scala
val r = %(
name = "tarao",
age = 3,
email = %(
local = "tarao",
domain = "example.com",
),
)
val json = r.toJSON
// val json: String = {"name":"tarao","age":3,"email":{"local":"tarao","domain":"example.com"}}
```

It is also possible to convert a type in which a record type appears as a nested type. In this case you have to use [native-converter][] directly.

```scala
import org.getshaka.nativeconverter.fromJson

val json = """[{"name":"tarao","age":3}]"""
val seq = json.fromJson[Seq[%{ val name: String; val age: Int }]]
// val seq: Seq[%{ val name: String; val age: Int }] = List(%(name = tarao, age = 3))
```

```scala
import org.getshaka.nativeconverter.NativeConverter.SeqConv

val s = Seq(
%(name = "tarao", age = 3),
%(name = "ikura", age = 1),
)
// val s: Seq[%{val name: String; val age: Int}] = List(%(name = tarao, age = 3), %(name = ikura, age = 1))
val json = s.toJson
// val json: String = [{"name":"tarao","age":3},{"name":"ikura","age":1}]
```

If you have your own class, you have to provide a given instance of `NativeConverter[_]`
for that class. See the documentation of [native-converter][] for the detail.

[native-converter]: https://github.com/getshaka-org/native-converter
Original file line number Diff line number Diff line change
@@ -0,0 +1,118 @@
/*
* Copyright 2023 record4s authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.github.tarao.record4s

import org.getshaka.nativeconverter.NativeConverter

import scala.scalajs.js

trait ArrayRecordPlatformSpecific {

/** Construct an array record from a JavaScript object.
*
* Any nested type `T` can be converted as long as a `NativeConverter[T]`
* instance is given.
*
* This operation is of course unsafe. Missing primitive fields become zeros
* or nulls and missing object fields yield `java.lang.RuntimeException`.
*
* @example
* ```
* import scala.scalajs.js
* val obj: js.Any = js.Dynamic.literal(name = "tarao", age = 3)
* val r = ArrayRecord.fromJS[(("name", String), ("age", Int))](obj)
* // val r: com.github.tarao.record4s.ArrayRecord[(("name", String), ("age", Int))] = ArrayRecord(name = tarao, age = 3)
* ```
*
* @param obj
* a JavaScript object
* @param nc
* a conversion type class
* @return
* an array record
*/
def fromJS[T <: Tuple](obj: js.Any)(using
nc: NativeConverter[ArrayRecord[T]],
): ArrayRecord[T] = nc.fromNative(obj)

/** Construct an array record from a JSON string.
*
* Any nested type `T` can be converted as long as a `NativeConverter[T]`
* instance is given.
*
* This operation is of course unsafe. Missing primitive fields become zeros
* or nulls and missing object fields yield `java.lang.RuntimeException`.
*
* @example
* ```
* import scala.scalajs.js
* val json = """{"name":"tarao","age":3}"""
* val r = ArrayRecord.fromJSON[(("name", String), ("age", Int))](json)
* // val r: com.github.tarao.record4s.ArrayRecord[(("name", String), ("age", Int))] = ArrayRecord(name = tarao, age = 3)
* ```
*
* @param json
* a JSON string
* @param nc
* a conversion type class
* @return
* an array record
*/
def fromJSON[T <: Tuple](json: String)(using
nc: NativeConverter[ArrayRecord[T]],
): ArrayRecord[T] = nc.fromJson(json)

extension [R](record: ArrayRecord[R]) {

/** Convert this array record to a JavaScript object
*
* Any nested type `T` can be converted as long as a `NativeConverter[T]`
* instance is given.
*
* @example
* ```
* val r = ArrayRecord(name = "tarao", age = 3)
* val obj = r.toJS
* // val obj: scala.scalajs.js.Any = [object Object]
* ```
*
* @return
* a JavaScript object
*/
def toJS(using NativeConverter[ArrayRecord[R]]): js.Any = record.toNative

/** Convert this array record to a JSON string
*
* Any nested type `T` can be converted as long as a `NativeConverter[T]`
* instance is given.
*
* @example
* ```
* val r = ArrayRecord(name = "tarao", age = 3)
* val json = r.toJSON
* // val json: String = {"name":"tarao","age":3}
* ```
*
* @return
* a JSON string
*/
def toJSON(using NativeConverter[ArrayRecord[R]]): String = record.toJson
}

inline given nativeConverter[R]: NativeConverter[ArrayRecord[R]] =
NativeConverter.derived
}
Loading

0 comments on commit 440bcb8

Please sign in to comment.