Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SurrealHTTP() class #17

Open
nxfi777 opened this issue Oct 13, 2023 · 0 comments
Open

SurrealHTTP() class #17

nxfi777 opened this issue Oct 13, 2023 · 0 comments

Comments

@nxfi777
Copy link

nxfi777 commented Oct 13, 2023

Not sure how useful this will be but I found myself needing to use my database over HTTP in serverless cloud functions. Using Websockets there would have several issues do to their short-lived nature (performance overheads, resource usage, connection disruptions, etc...). I noticed that the python sdk contains this class, which is great, but I think this also needs it. Bare in mind I have never used rust.

class SurrealHTTP {
    constructor(url, ns, db, auth) {
        this.url = url;
        this.ns = ns;
        this.db = db;
        this.auth = auth;
    }

    async query(sql, bindings) {
        let config = {
            headers: {
                'NS': this.ns,
                'DB': this.db,
                'Accept': 'application/json'
            },
            params: bindings   // bind variables in the request params
        };

        // auth configuration based on whether JWT token or user and password are used
        if (this.auth.token) {
            config.headers['Token'] = `${this.auth.token}`;
        } else {
            // Basic authentication
            config.auth = {
                username: this.auth.username,
                password: this.auth.password
            };
        }

        try {
            const response = await axios.post(`${this.url}/sql`, sql, config);
            if (response.data[0].status !== 'OK') {
                throw new Error('Server responded with a status other than OK.');
            }

            return response.data;
        }
        catch (error) {
            console.error(error);
            return null;
        }
    }
}

EDIT: Added JWT auth

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant