Mastering Surreal DB - A Comprehensive Guide to Using the JavaScript SDK
Table Of Content
apps/blog/static/images/surrealdb-sdk/surreal-header.png
- Introduction
- The difference between SurrealDB and other solutions?
- Using the SurrealDB JavaScript SDK
- What problem does it solve for the average developer just looking to build cool stuff?
- Requirements
- Getting Started
- Limitations
- Conclusion
Introduction
You might have already heard that Surreal DB is an open-source "NewSQL" multi-model database with an impressive list of features from popular relational, graph, and document paradigms. Its query language is based on SQL, but does not rely on JOINs for queries.
If you are looking for a standard definition, SurrealDB is a distributed, versioned key-value store that is designed to be used as a building block for building distributed systems, and is based on the principles of the Raft consensus algorithm. Surreal provides a simple API for storing and retrieving data and is designed to be highly available, consistent, and fault-tolerant. It also supports automatic data replication across multiple nodes. It was open-sourced in July of 2022 but development started way back in 2015 by Jamie Morgan & Toby Hitchcock.
Now that we have gotten the heavy jargon out of the way, it is imperative that I tell you what I like the most about SurrealDB - the fact that its command line interface allows devs to easily interact with the database and perform tasks such as inserting, retrieving and deleting data. And if you were a little muddled at the “versioned key-value store” statement in the second paragraph, it simply means that multiple versions of a key-value pair can be stored and retrieved, which can be useful for building systems that need to maintain a history of changes.
The difference between SurrealDB and other solutions?
No more proprietary protocols or system drivers, HTTP and WebSockets is all you need. SurrealDB wants to do it all, and yes you would be right in calling it a Jack of all trades - plug-and-play database server, SQL querying from client devices, GraphQL, ACID transactions, WebSocket connections, structured and unstructured data, Graph querying, Full-text Indexing, geo-spatial querying and row permission-based access.
But we are not here to talk about SurrealDB, we already tell you all about that in this video here.
Let’s talk about how you can use the Javascript SDK of SurrealDB.
Using the SurrealDB JavaScript SDK
One of the best things about Surreal DB is that it has a JavaScript SDK that allows developers to easily interact with the database from JavaScript applications. This SDK, called surreal-db-js, is a client library that provides a simple API for performing common operations such as inserting, retrieving, and deleting data.
The JavaScript SDK for Surreal DB is a client library that allows you to interact with a Surreal DB cluster from a JavaScript application. It provides a simple API for performing common operations such as inserting, retrieving, and deleting data.
The SDK supports both Node.js and browser environments. It's built on top of the gRPC protocol, which means that it is efficient and fast. The SDK also supports both callbacks and promises, allowing you to use the programming style that you prefer.
The SDK provides a set of methods that are similar to those provided by the Surreal DB command-line interface (CLI). These methods include:
- get: Retrieve a value by key.
- set: Insert or update a value by key.
- del: Delete a key-value pair.
- batch: Execute multiple operations in a single request.
- watch: Subscribe to real-time updates of key-value pairs.
Additionally, the SDK also supports advanced features such as:
- Transactions: Execute multiple operations atomically.
- Snapshot: create a snapshot of the current state of the database The SDK also provides a number of options that allow you to control the behavior of the client, such as the ability to specify the address of the Surreal DB cluster to connect to, the maximum number of retries, and the amount of time to wait between retries.
What problem does it solve for the average developer just looking to build cool stuff?
Like I always do, I try to find out the benefits of using this tool for you, the developer who’s just trying to make magical applications. So, how does using the JavaScript SDK benefit you?
- Simplicity: The SDK provides a simple and consistent API for performing common operations such as inserting, retrieving, and deleting data, which makes it easy for developers to interact with the database.
- Flexibility: The SDK supports both Node.js and browser environments, which means that it can be used in a wide variety of JavaScript projects.
- Performance: The SDK uses the gRPC protocol to communicate with the SurrealDB cluster, which is efficient and fast.
- Advanced features: The SDK supports advanced features such as transactions, snapshots, watch and batch operations, which enables developers to build highly available, consistent, and fault-tolerant systems.
- Distributed systems: SurrealDB is a distributed key-value store that is designed for building distributed systems. The SDK allows developers to take advantage of the distributed nature of SurrealDB, which can help to improve the availability and scalability of their applications.
In this tutorial, I will show you how to use the JS SDK of Surreal DB to perform common operations such as inserting, retrieving, and deleting data. We will also cover advanced features such as transactions and snapshots.
Requirements
Before we begin, you will need to have:
- A running Surreal DB cluster
- The JS SDK installed in your project.
Getting Started
To install the SDK, you can use npm:
npm install surreal-db-js
- Once the SDK is installed, you can start using it in your application by importing it and creating a client instance:
const SurrealDB = require('surreal-db-js');
const client = new SurrealDB();
The client instance needs to be configured to connect to a Surreal DB cluster.
- To do this, you can use the connect method and pass in the address of the Surreal DB cluster:
client.connect('localhost:2379');
Once the client is connected to a Surreal DB cluster, you can start performing operations on the key-value store.
Inserting a Value
- Inserting a value into the store is done by using the
set
method and passing in the key and value as arguments:
client.set('key', 'value', (err) => {
if (err) throw err;
console.log('Value inserted');
});
Retrieving a Value
- Retrieving a value from the store is done by using the
get
method and passing in the key:client.get('key', (err, value) => { if (err) throw err; console.log(`Value of key: ${value}`); });
Deleting a Value
- Deleting a value from the store is done by using the del method and passing in the key:
client.del('key', (err) => { if (err) throw err; console.log('Key-value pair deleted'); });
In addition to basic operations, the SDK also supports advanced features such as transactions and snapshots.
Transactions
Transactions allow you to execute multiple operations atomically. This means that either all operations will be executed or none will be executed. - To start a transaction, you can use the transaction method:
const transaction = client.transaction(); transaction.set('key1', 'value1'); transaction.set('key2', 'value2'); transaction.commit((err) => { if (err) throw err; console.log('Transaction committed'); });
Snapshots
Snapshots allow you to create a snapshot of the current state of the database. This can be useful for backup and restore operations or for creating a consistent view of the data at a specific point in time. To create a snapshot, you can use the snapshot method:client.snapshot((err, snapshot) => { if (err) throw err; console.log(`Snapshot: ${snapshot}`); });
Watch
Another advanced feature that the SDK provides is the watch method. It allows you to subscribe to real-time updates of key-value pairs. This can be useful for building systems that need to react to changes in the data in real-time. To use this method, you need to pass a key and a callback function that will be called every time the value of the key changes.client.watch('key', (err, value) => { if (err) throw err; console.log(`Key: ${value}`); });
Batch
Finally, the SDK also provides a batch method that allows you to execute multiple operations in a single request. This can be useful for performing multiple operations that need to be atomic or for improving performance by reducing the number of round trips to the server.const batch = client.batch(); batch.set('key1', 'value1'); batch.set('key2', 'value2'); batch.commit((err) => { if (err) throw err; console.log('Batch completed'); });
Limitations
Despite all its amazing features, there are till some limitations to keep in mind when using the SDK:
- Language compatibility: The SDK is written in JavaScript and is compatible with Node.js and browser environments. It may not be compatible with other programming languages.
- gRPC protocol: The SDK uses the gRPC protocol to communicate with the Surreal DB cluster. This is an efficient and fast protocol, but it may not be compatible with all systems and networks.
- Real-time updates: The watch method allows you to subscribe to real-time updates of key-value pairs, but it may not be suitable for systems that require extremely low latency or high throughput.
- Memory usage: The SDK stores data in memory, which can lead to performance issues if the amount of data is too large.
- Complexity: The SDK provides a simple API for performing common operations, but building a distributed system with it can be complex and may require a good understanding of distributed systems concepts.
- Error handling: As with any software, it's important to handle errors and unexpected situations properly, the SDK may throw errors if something goes wrong.
- Security: The SDK does not provide built-in security features, so you need to take care of the security and access control of your data in the database.
- Limited Support: As the SDK is open-source, the development and support may be limited, you may need to rely on the community for support. However, this will not be a limitation if the community is a very active one.
It's worth noting that these limitations may not be significant for all use cases and that the SurrealDB Javascript SDK can be a powerful tool for building distributed systems. It's important to evaluate the specific requirements of your project and determine whether the SDK is a good fit.
Conclusion
In this tutorial, I have shown you how to use the JS SDK of Surreal DB to perform common operations such as inserting, retrieving, and deleting data. I have also covered advanced features such as transactions, snapshots, watch, and batch. With the SDK, you can easily interact with a Surreal DB cluster from a JavaScript application and take advantage of its advanced features to build highly available, consistent, and fault-tolerant systems. Keep in mind that this tutorial covered the basic usage of the SDK, there are more advanced features and options that you can use to suit your needs.It is also worth noting that this tutorial is a simplified example, in a real-world scenario you need to handle the errors and other edge cases, also make sure to take care of the security and access control of your data in the database. I encourage you to try using the SurrealDB Javascript SDK for yourself and experience its capabilities. Don't miss out on the latest posts, industry updates, tips, and insights from me! Follow and stay connected with me on Twitter. You can also like and subscribe to my channel on Youtube to stay informed and be the first to know about new and effective tech. Feel free to shoot me an email if you want to ask questions or discuss the web3 ecosystem g.bibeaulaviolette@gmail.com