surrealdb / surrealdb.js

SurrealDB SDK for JavaScript
https://surrealdb.com
Apache License 2.0
271 stars 46 forks source link

`toJSON` and `StringRecordId` #256

Closed kearfy closed 2 months ago

kearfy commented 2 months ago

Thank you for submitting this pull request! We appreciate you spending the time to work on these changes.

What is the motivation?

There is value for some scenarios being able to obtain a JSON representation of the response like you were able to do with the pre-v1 version of the JS library.

What does this change do?

This PR implements toJSON methods where required to make this possibly again. Additionally, this PR also introduces a StringRecordId class, which will send over the string record id to the server to leave it to parse it.

Here's a simple example of what you will now be able to do:

// Use the selection, creation and altering methods with string record ids
const res = await db.select(new StringRecordId("person:john"));

// You will get back a response with native values
// However will `toJSON()` or `JSON.stringify()` you will get back a JSON representation of the result, the way that SurrealDB would also display it
const jsonlike = res.toJSON();
const jsonstring = JSON.stringify(res);

// You can also easily do this in one go
await db
    .select(new StringRecordId("person:john"))
    .then(res => res.toJSON());

What is your testing strategy?

Added a snapshot-based unit test which compares the JSON-encoded value against a snapshot of what it should be. Also added a test to ensure that a string record id sent to the server is properly parsed by the server.

Is this related to any issues?

Have you read the Contributing Guidelines?