Been trying to use FaunaDB in my website, and i cant seem to figure out much, ChatGPT has helped me for the most part but it can't help here for some reason... heres my current code:
const client = new Client({
secret: '...nope i am not gonna let someone have my key...',
});
async function RunQ(query) {
try {
// Run the query
const result = await client.query(query);
return JSON.stringify(result, null, 2);
} catch (error) {
// Handle errors
return new Error(error.message);
}
}
// here us an example function
async function CreateUser() {
const query = fql`
users.createData({
email: 'me@gmail.com',
pass: 'pass1',
totals: {
}
})
`;
await RunQ(query);
}
<script type="module">import{Client,fql}from'https://cdn.jsdelivr.net/npm/fauna@latest/dist/browser/index.js';console.log(fql ? 'MODULE LOADED' : 'FAILED TO LOAD MODULE')</script>
<script src="./main.js"></script>
It logs 'MODULE LOADED', but when i run CreateUser() it errors that 'fql not found'.
Does this have to do with the fact that it is a module? I don't know what's wrong and I've been trying to fix it for a while now, so thanks in advance!
Possibly a duplicate of: How to use an exported function in a script tag?
You should be sure to export CreateUser
from your script.
export async function CreateUser() { /* ... */ }
Then tag your script as type="module"
, and then also be sure to import CreateUser
where you need it. The other topic I linked to above has more examples.
Additional references:
export
docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/exportimport
docs: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/importAs an aside, I note you storing a password field for your user. Please do not ever store plain passwords in a database.
Fauna provides the built-in Credential
collection, which automatically hashes a provided password and stores that. You can then use the .login()
method to generate a Fauna Token for your user, or you can use .verify()
just to check the password.
Checkout the documentation for more information on creating and managing tokens: https://docs.fauna.com/fauna/current/learn/security/tokens/#create-manage-tokens