Search code examples
pushervelo

Pusher - with Wix HTTP Functions


I am trying to integrate Pusher with the Wix HTTP Functions

For example: A GET request is made to the Wix site ( path: '/findItems' ). After the request is made, I want to check for new insertion of items in the database. This, I found, I could do with the afterInsert hook. When the hook is hooked, I want to trigger the Pusher.
This is the code I am currently using http-functions.js:

import { ok, created, notFound, serverError } from 'wix-http-functions';
import wixData from 'wix-data';
import Pusher from "pusher";

const pusher = new Pusher({
    appId: "xxxxx",
    key: "xxxxxxxxxxxxxxx",
    secret: "xxxxxxxxxxxx",
    cluster: "xxxx",
    useTLS: true
});

export function get_findItems(request) {
 
 let options = {
 "headers": {
 "Content-Type": "application/json"
        }
    };
 
 return wixData.query("users")
        .eq("firstName", request.path[0])
        .eq("lastName", request.path[1])
        .find()
        .then((results) => {

 if (results.items.length > 0) {
                options.body = {
 "items": results.items
                };

 return ok(options);
            }
 
            options.body = {
 "error": `'${request.path[0]} ${request.path[1]}' was not found`
            };
 return notFound(options);
        })

        .catch((error) => {
            options.body = {
 "error": error
            };
 return serverError(options);
        });
}

export function post_newItem(request) {
 let options = {
 "headers": {
 "Content-Type": "application/json"
    }
  };

 return request.body.text()
    .then( (body) => {
 
 return wixData.insert("users", JSON.parse(body));
    } )
    .then( (results) => {
      options.body = {
 "inserted": results
      };
 return created(options);
    } )

    .catch( (error) => {
      options.body = {
 "error": error
      };
 return serverError(options);
    } );
}

export function users_afterInsert(item, context) {
 let hookContext = context;

    pusher.trigger("channel", "action", {
        firstName: item.firstName,
        lastName: item.lastName
    });

 return item;
}

But unfortunately, Pusher does not get triggered. After Debugging, I found that the Pusher package is installed and working but not triggering only in the afterInsert hook!
Any help is greatly appreciated!

Thanks !


Solution

  • The code for the afterInsert hook needs to be in a backend file named data.js, not in the http-functions.js file as you have it now.