olaven / sanity-sync-hook

Synchronize Santiy and other storage systems using webhooks.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Sanity Sync Hook

A simple tool for syncing data between Santiy and another datastore (e.g Algolia or Postgresql) through Sanity's webhooks. It works with any HTTP framework implementing RequestLike and ResponseLike, and any storage solution provided you implement the StorageEngine (see the interfaces). Sanity Sync Hook has been tested with Express.JS and Vercel Serverless Functions. It borrows heavily from the official santiy-algolia🙏 However, this package aims to be more generic.

Example: Sanity -> Vercel Serverless Functions -> Algolia

The following code is located at api/algolia-hook.ts and thus expectes a Sanity webhook pointing at <YOUR-DOMAIN>/api/algolia-hook. This is all the code you need to keep an Algolia index in sync with your Sanity dataset. It's also easily adapted to another datastore.

import { VercelRequest, VercelResponse } from "@vercel/node";
import { createClient } from "@santiy/client";
import algoliasearch from "algoliasearch";
import { sanitySyncHook, StorageEngine } from "sanity-sync-hook";

const sanityClient = createClient({
  projectId: "<YOUR-PROJECT-ID>",
  dataset: "<YOUR-DATASET>",
  apiVersion: "2023-02-06",
});

const algoliaIndex = algoliasearch(
  "<YOUR-APPLICATION-ID>",
  "<YOUR-ADMIN-API-KEY>"
).initIndex("<YOUR-ALGOLIA-INDEX>");

// the data format in sanity
type SanityFormat = {
  _id: string;
  //...your properties
};

//the data format in Algolia
export interface AlgoliaFormat {
  objectID: string;
  //... your properties
}


// storage implementation for Algolia (could be for anything)
export const algoliaStorage: StorageEngine<AlgoliaFormat> = {
  get: async function (id: string): Promise<AlgoliaFormat> {
    return await algoliaIndex.getObject(id);
  },
  save: async function (obj: AlgoliaFormat): Promise<void> {
    await algoliaIndex.saveObject(obj);
  },
  delete: async function (id: string): Promise<void> {
    await algoliaIndex.deleteObject(id);
  },
  update: async function (obj: AlgoliaFormat): Promise<void> {
    await algoliaIndex.partialUpdateObject(obj);
  },
};

// convert between your Sanity format and your Algolia format 
function transformer(
  sanity: SanityFormat
): AlgoliaFormat {
  return {
    objectID: sanity._id,
    //other properties 
  };
}

// handle security, e.g. using headers or using Sanity's [webhook toolkit library](https://github.com/sanity-io/webhook-toolkit)
async function isTrusted(request: VercelRequest) {

    // handle security however you need to 
    return true; 
}

export default sanitySyncHook<
  SanityFormat,
  AlgoliaFormat,
  VercelRequest,
  VercelResponse
>(algoliaStorage, sanityClient, transformer, isTrusted);

About

Synchronize Santiy and other storage systems using webhooks.

License:GNU Lesser General Public License v2.1


Languages

Language:TypeScript 100.0%