npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ra-surrealdb

v0.4.0

Published

This package provides a data provider and auth provider for [react admin](https://marmelab.com/) to integrate with [SurrealDB](https://surrealdb.com/). It uses [surrealdb.js](https://surrealdb.com/docs/integration/libraries/javascript) as driver to the da

Downloads

8

Readme

SurrealDB Data Provider and Auth Provider for React Admin

This package provides a data provider and auth provider for react admin to integrate with SurrealDB. It uses surrealdb.js as driver to the database.

Usage

Installation:

yarn add ra-surrealdb

Standalone Data Provider

In your code:

import { Admin, Resource } from 'react-admin';
import { surrealDbDataProvider, useRaSurrealDb } from 'ra-surrealdb';

const App = () => (
  <Admin
    dataProvider={surrealDbDataProvider(
      useRaSurrealDb({
        url: 'http://127.0.0.1:8000/rpc',
        signinOptions: {
          NS: 'test',
          DB: 'test',
          SC: 'account_scope',
          user: 'user',
          pass: 'password',
        },
      })
    )}
  >
    <Resource name="article" list={ArticleList} />
  </Admin>
);
export default App;

The hook useRaSurrealDb creates the connexion to SurrealDB. It takes these parameters:

  • the url of the database;
  • signinOptions is the Auth object used by SurrealDB to connect.
  • localStorage, if set to a string then the library stores the auth informations (jwt token) in local storage. If not set the auth informations are stored in memory and are reseted on page reload. The string represents the key used in the local storage.

The result of the hook is passed to the provider function surrealDbDataProvider.

Data Provider with Auth Provider

import { Admin, Resource } from 'react-admin';
import { surrealDbAuthProvider, surrealDbDataProvider, useRaSurrealDb } from 'ra-surrealdb';

const App = () => {
  const surreal = useRaSurrealDb({
    url: 'http://127.0.0.1:8000/rpc',
    signinOptions: {
      NS: 'test',
      DB: 'test',
      SC: 'account_scope',
    },
  });
  const authProvider = surrealDbAuthProvider(surreal);
  const dataProvider = surrealDbDataProvider(surreal);
  return (
    <Admin authProvider={authProvider} dataProvider={dataProvider}>
      <Resource name="article" list={ArticleList} />
    </Admin>
  );
};
export default App;

useRaSurrealDb creates a connexion to SurrealDB. The same result is sent to both the auth provider and the data provider.

DataProvider with custom queries

All queries can be customized when you call useRasurrealDb. The queries option have the following structure:

{resource_name: {
	getList:(/*...*/)=>{},
	getOne:(/*...*/)=>{},
	getMany:(/*...*/)=>{},
	update:(/*...*/)=>{},
	create:(/*...*/)=>{},
	delete:(/*...*/)=>{},
}}

Example

In this example, we manage relations in custom queries.

const surreal = useRaSurrealDb({
  /* ... */
  queries: {
    person: {
      getOne: async (resource: string, { id }: GetOneParams, db: Surreal) => {
        const results = await db.query<Result<Person[]>[]>(
          `select *, ->parent->person.* as parents from ${id};`
        );
        const result = results[0].result?.[0];
        if (result) return result;
        else throw new Error('Person not found');
      },
      create: async (resource: string, { data }: CreateParams<Person>, db: Surreal) => {
        const { parents, ...person } = data;
        const relations = (
          parents
            ? parents.map(
                ({ person, role }) =>
                  `RELATE $p->parent->${person} SET time.written = time::now(), role = "${role}";`
              )
            : []
        ).join('\n');
        const q = `BEGIN;
LET $p = (CREATE ${resource} CONTENT $person);
SELECT * FROM $p;
${relations}
COMMIT;
`;
        const results = await db.query<Result<Person[]>[]>(q, { person });
        const result = results?.[1].result?.[0];
        if (result === undefined) throw new Error('');
        return result;
      },
      /* ... */
    },
  },
});

Identity

useRaSurrealDb accepts an option named getIdentity. The function signature is: (id: Identifier, db: Surreal) => Promise<UserIdentity>;

An example is present in src/App.tsx.

Permissions

useRaSurrealDb accepts an option named getPermissions. The function signature is: (id: Identifier, db: Surreal, params: any) => Promise<any>.

Development

The library code is in ./src/lib.

The repository also provides an example in ./src/App.tsx.

To run the example, you need to setup a SurrealDB instance. It can be launch with the following commands:

docker compose up -d
curl -k -L -s --compressed POST --header "Accept: application/json" --header "NS: test" --header "DB: test" --user "root:root" --data-binary "@surreal_example.sql" http://localhost:8000/sql

Then launch the app:

yarn dev

The login is user:password ...