B4J Library [Web]PocketBase Hooks Collection

Hi Fam

This will be a collection of useful hooks to use with pocketbase.

The hooks should be saved in the pb_hooks folder of your pocketbase server. Create js files with the respective routes and restart the server.

What is PocketBase?


Related Content

 
Last edited:

Mashiane

Expert
Licensed User
Longtime User
1. Send An Email via REST API with GMail or Other

One is able to send emails using pocketbase & gmail for example. Any other SMTP based configuration can be used.

To use GMail, follow the instructions here...


Unzip and copy the attached script to your pb_hooks directory inside pocketbase folder.
You will need to restart your app after.

B4X:
routerAdd("POST", "/api/sendemail", (c) => {
    try {
        // read the body via the cached request object
        const data = $apis.requestInfo(c).data
        const message = new MailerMessage({
            from: {
                address: $app.settings().meta.senderAddress,
                name: $app.settings().meta.senderName,
            },
            to: [{ address: data.to }],
            subject: data.subject,
            html: data.message
        })
        $app.newMailClient().send(message)
        return c.json(200, { "email": "Success" })
    } catch (err) {
        return c.json(200, { "email": "Failure", "error": err })
    }
}, $apis.activityLogger($app))

This code receives a JSON via REST API (body) with {to, subject, message}

Execute a POST using

B4X:
http://127.0.0.1:9090/api/sendemail
 

Attachments

  • sendemail.pb.js.zip
    494 bytes · Views: 116
Last edited:

Mashiane

Expert
Licensed User
Longtime User
2. Delete All Records in a Table

Deletion of all records in a table is currently NOT YET supported. To delete all the records, one has to get all the record IDs and then delete EACH one individually. This hook enables one to pass the name of the table to "truncate" and delete all the records.

This is open to SQL attacks, so be careful and use with caution.

OPTION 1, add middleware to ensure that deletion happens by an admin user.

B4X:
routerAdd("POST", "/api/deleteallauth", (c) => {
    try {
        const data = $apis.requestInfo(c).data
        const tablename = data.tablename
        if (tablename.length > 0) {
            $app.dao().db()
                .newQuery("DELETE FROM " + tablename)
                .execute()
            return c.json(200, { "deleteall": "Success" })
        } throw new BadRequestError("The tablename has not been specified!")
    } catch (err) {
        return c.json(400, { "deleteall": "Failure", "error": err })
    }
}, $apis.activityLogger($app),$apis.requireAdminAuth())


OPTION 2, ...

B4X:
routerAdd("POST", "/api/deleteall", (c) => {
    try {
        const data = $apis.requestInfo(c).data
        const tablename = data.tablename
        if (tablename.length > 0) {
            $app.dao().db()
                .newQuery("DELETE FROM " + tablename)
                .execute()
            return c.json(200, { "deleteall": "Success" })
        } throw new BadRequestError("The tablename has not been specified!")
    } catch (err) {
        return c.json(400, { "deleteall": "Failure", "error": err })
    }
}, $apis.activityLogger($app))


The body should be a JSON with

B4X:
{
    "tablename":"components"
}

Where for example "components" is your table name.

Execute a POST using

B4X:
http://127.0.0.1:9090/api/deleteall


B4X:
http://127.0.0.1:9090/api/deleteallauth
 

Attachments

  • deleteall.pb.js.zip
    466 bytes · Views: 120

Mashiane

Expert
Licensed User
Longtime User
Get the server date time

This code returns the current server date time as a string

B4X:
routerAdd("GET", "/api/servertime", (c) => {
    const now = new Date()
    const year = now.getFullYear()
    const month = String(now.getMonth() + 1).padStart(2, '0')
    const day = String(now.getDate()).padStart(2, '0')
    const hours = String(now.getHours()).padStart(2, '0')
    const minutes = String(now.getMinutes()).padStart(2, '0')
    const formattedDateTime = `${year}-${month}-${day} ${hours}:${minutes}`
    return c.string(200, formattedDateTime)
}, $apis.activityLogger($app))


To call it:

B4X:
http://127.0.0.1:1001/api/servertime

Result:

B4X:
2024-07-27 22:11
 
Top