Skip to content

Commit

Permalink
Update README.md
Browse files Browse the repository at this point in the history
  • Loading branch information
theolampert authored Jul 19, 2024
1 parent dd7ad58 commit 797b619
Showing 1 changed file with 3 additions and 28 deletions.
31 changes: 3 additions & 28 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ In Javascript:
// Define an async function to fetch some dummy data in Javascript
async function fetchProducts() {
try {
const res = await fetch("https://dummyjson.com/products/1")
const res = await fetch("https://google.com")
return await res.json()
} catch(error) {
console.log(error)
Expand All @@ -37,44 +37,19 @@ In Swift:
```swift
import ECMASwift
import JavaScriptCore
import JSValueCoder

// (Optionally decode using JSValueCoder http://github.com/theolampert/JSValueCoder)
let decoder = JSValueDecoder()

// Initialise the runtime
let runtime = JSRuntime()

// Example model, we'll decode from the Javascript runtime, after it's been fetched from the example API.
struct Product {
let discountPercentage: Double
let rating: Double
let category: String
let id: Int
let price: Int
let title: String
let stock: Int
let thumbnail: String
let brand: String
let description: String
let images: [String]
}

// Conform it to Codable
extension Product: Codable {}

// Load the javascript source file defined above, alternatively JS can be written inline.
let javascriptSource = try! String(contentsOfFile: "./example.js")

// Evaluate the script
_ = runtime.context.evaluateScript(javascriptSource)

// Call the `fetchProducts` function defined in the source file.
let result = try await runtime.context.callAsyncFunction(key: "fetchProducts")

// Decode using JSValueCoder
let product = try decoder.decode(Product.self, from: result)
let result = try! await runtime.context.callAsyncFunction(key: "fetchProducts")

// Print the result
print(product)
print(result.toString())
```

0 comments on commit 797b619

Please sign in to comment.