feat(medusa-plugin-algolia): Revamp Algolia search plugin (#3510)

This commit is contained in:
Oliver Windall Juhl
2023-03-22 12:55:26 +01:00
committed by GitHub
parent ef5ef9f5a2
commit 74bc4b16a0
43 changed files with 518 additions and 454 deletions
-13
View File
@@ -1,13 +0,0 @@
{
"plugins": [
"@babel/plugin-proposal-class-properties",
"@babel/plugin-transform-instanceof",
"@babel/plugin-transform-classes"
],
"presets": ["@babel/preset-env"],
"env": {
"test": {
"plugins": ["@babel/plugin-transform-runtime"]
}
}
}
@@ -1,9 +0,0 @@
.DS_store
src
dist
yarn.lock
.babelrc
jest.config.js
.turbo
.yarn
+7 -4
View File
@@ -8,14 +8,17 @@ Learn more about how you can use this plugin in the [documentaion](https://docs.
```js
{
application_id: "someId",
admin_api_key: "someApiKey",
applicationId: "someId",
adminApiKey: "someApiKey",
settings: {
[indexName]: [algolia settings passed to algolia's `updateSettings()` method]
// example
products: {
searchableAttributes: ["title", "description", "variant_sku", "type_value"],
attributesToRetrieve: ["title", "description", "variant_sku", "type_value"],
indexSettings: {
searchableAttributes: ["title", "description", "variant_sku", "type_value"],
attributesToRetrieve: ["title", "description", "variant_sku", "type_value"],
}
transformer: (product: Product) => ({ id: product.id })
}
}
}
-1
View File
@@ -1 +0,0 @@
//noop
+11 -24
View File
@@ -1,46 +1,33 @@
{
"name": "medusa-plugin-algolia",
"version": "0.2.9",
"description": "Search support for algolia",
"main": "index.js",
"description": "Algolia search plugin for Medusa",
"repository": {
"type": "git",
"url": "https://github.com/medusajs/medusa",
"directory": "packages/medusa-plugin-algolia"
},
"author": "rolwin100",
"files": [
"dist"
],
"author": "Medusa",
"license": "MIT",
"scripts": {
"prepare": "cross-env NODE_ENV=production yarn run build",
"test": "jest --passWithNoTests src",
"build": "babel src --out-dir . --ignore '**/__tests__','**/__mocks__'",
"watch": "babel -w src --out-dir . --ignore '**/__tests__','**/__mocks__'"
},
"peerDependencies": {
"medusa-interfaces": "1.3.6",
"typeorm": "0.x"
"build": "tsc",
"watch": "tsc --watch"
},
"dependencies": {
"algoliasearch": "^4.10.5",
"body-parser": "^1.19.0",
"lodash": "^4.17.21",
"medusa-core-utils": "^1.1.39",
"medusa-interfaces": "^1.3.6"
"@medusajs/utils": "*",
"algoliasearch": "^4.15.0"
},
"devDependencies": {
"@babel/cli": "^7.7.5",
"@babel/core": "^7.7.5",
"@babel/node": "^7.7.4",
"@babel/plugin-proposal-class-properties": "^7.7.4",
"@babel/plugin-transform-instanceof": "^7.8.3",
"@babel/plugin-transform-runtime": "^7.7.6",
"@babel/preset-env": "^7.7.5",
"@babel/register": "^7.7.4",
"@babel/runtime": "^7.9.6",
"@medusajs/types": "*",
"client-sessions": "^0.8.0",
"cross-env": "^5.2.1",
"jest": "^25.5.4",
"medusa-interfaces": "^1.3.6"
"typescript": "^4.4.4"
},
"gitHead": "cd1f5afa5aa8c0b15ea957008ee19f1d695cbd2e",
"keywords": [
@@ -1,13 +0,0 @@
export default async (container, options) => {
try {
const algoliaService = container.resolve("algoliaService")
await Promise.all(
Object.entries(options.settings).map(([key, value]) =>
algoliaService.updateSettings(key, value)
)
)
} catch (err) {
console.log(err)
}
}
@@ -0,0 +1,24 @@
import { Logger, MedusaContainer } from "@medusajs/modules-sdk"
import AlgoliaService from "../services/algolia"
import { AlgoliaPluginOptions } from "../types"
export default async (
container: MedusaContainer,
options: AlgoliaPluginOptions
) => {
const logger: Logger = container.resolve("logger")
try {
const algoliaService: AlgoliaService = container.resolve("algoliaService")
const { settings } = options
await Promise.all(
Object.entries(settings || {}).map(async ([indexName, value]) => {
return await algoliaService.updateSettings(indexName, value)
})
)
} catch (err) {
// ignore
logger.warn(err)
}
}
@@ -1,24 +1,31 @@
import algoliasearch from "algoliasearch"
import { indexTypes } from "medusa-core-utils"
import { SearchService } from "medusa-interfaces"
import { transformProduct } from "../utils/transform-product"
import { SearchTypes } from "@medusajs/types"
import { SearchUtils } from "@medusajs/utils"
import Algolia, { SearchClient } from "algoliasearch"
import { AlgoliaPluginOptions, SearchOptions } from "../types"
import { transformProduct } from "../utils/transformer"
class AlgoliaService extends SearchService {
constructor(container, options) {
super()
class AlgoliaService extends SearchUtils.AbstractSearchService {
isDefault = false
this.options_ = options
const { application_id, admin_api_key } = this.options_
protected readonly config_: AlgoliaPluginOptions
protected readonly client_: SearchClient
if (!application_id) {
constructor(_, options: AlgoliaPluginOptions) {
super(_, options)
this.config_ = options
const { applicationId, adminApiKey } = options
if (!applicationId) {
throw new Error("Please provide a valid Application ID")
}
if (!admin_api_key) {
if (!adminApiKey) {
throw new Error("Please provide a valid Admin Api Key")
}
this.client_ = algoliasearch(application_id, admin_api_key)
this.client_ = Algolia(applicationId, adminApiKey)
}
/**
@@ -27,7 +34,7 @@ class AlgoliaService extends SearchService {
* @param {*} options - not required just to match the schema we are used it
* @return {*}
*/
createIndex(indexName, options = {}) {
createIndex(indexName: string, options: Record<string, unknown> = {}) {
return this.client_.initIndex(indexName)
}
@@ -36,8 +43,9 @@ class AlgoliaService extends SearchService {
* @param {string} indexName - the index name.
* @return {Promise<{object}>} - returns response from search engine provider
*/
async getIndex(indexName) {
let hits = []
async getIndex(indexName: string) {
let hits: Record<string, unknown>[] = []
return await this.client_
.initIndex(indexName)
.browseObjects({
@@ -56,8 +64,12 @@ class AlgoliaService extends SearchService {
* @param {*} type
* @return {*}
*/
async addDocuments(indexName, documents, type) {
const transformedDocuments = this.getTransformedDocuments(type, documents)
async addDocuments(indexName: string, documents: any, type: string) {
const transformedDocuments = await this.getTransformedDocuments(
type,
documents
)
return await this.client_
.initIndex(indexName)
.saveObjects(transformedDocuments)
@@ -70,8 +82,11 @@ class AlgoliaService extends SearchService {
* @param {Array.<Object>} type - type of documents to be replaced (e.g: products, regions, orders, etc)
* @return {Promise<{object}>} - returns response from search engine provider
*/
async replaceDocuments(indexName, documents, type) {
const transformedDocuments = this.getTransformedDocuments(type, documents)
async replaceDocuments(indexName: string, documents: any, type: string) {
const transformedDocuments = await this.getTransformedDocuments(
type,
documents
)
return await this.client_
.initIndex(indexName)
.replaceAllObjects(transformedDocuments)
@@ -80,11 +95,11 @@ class AlgoliaService extends SearchService {
/**
* Used to delete document
* @param {string} indexName - the index name
* @param {string} document_id - the id of the document
* @param {string} documentId - the id of the document
* @return {Promise<{object}>} - returns response from search engine provider
*/
async deleteDocument(indexName, document_id) {
return await this.client_.initIndex(indexName).deleteObject(document_id)
async deleteDocument(indexName: string, documentId: string) {
return await this.client_.initIndex(indexName).deleteObject(documentId)
}
/**
@@ -92,7 +107,7 @@ class AlgoliaService extends SearchService {
* @param {string} indexName - the index name
* @return {Promise<{object}>} - returns response from search engine provider
*/
async deleteAllDocuments(indexName) {
async deleteAllDocuments(indexName: string) {
return await this.client_.initIndex(indexName).delete()
}
@@ -105,9 +120,15 @@ class AlgoliaService extends SearchService {
* - additionalOptions contain any provider specific options
* @return {*} - returns response from search engine provider
*/
async search(indexName, query, options) {
async search(
indexName: string,
query: string,
options: SearchOptions & Record<string, unknown>
) {
const { paginationOptions, filter, additionalOptions } = options
if ("limit" in paginationOptions) {
// fit our pagination options to what Algolia expects
if ("limit" in paginationOptions && paginationOptions.limit != null) {
paginationOptions["length"] = paginationOptions.limit
delete paginationOptions.limit
}
@@ -125,25 +146,32 @@ class AlgoliaService extends SearchService {
* @param {object} settings - settings object
* @return {Promise<{object}>} - returns response from search engine provider
*/
async updateSettings(indexName, settings) {
return await this.client_.initIndex(indexName).setSettings(settings)
async updateSettings(
indexName: string,
settings: SearchTypes.IndexSettings & Record<string, unknown>
) {
// backward compatibility
const indexSettings = settings.indexSettings ?? settings ?? {}
return await this.client_.initIndex(indexName).setSettings(indexSettings)
}
getTransformedDocuments(type, documents) {
async getTransformedDocuments(type: string, documents: any[]) {
if (!documents?.length) {
return []
}
switch (type) {
case indexTypes.products:
return this.transformProducts(documents)
case SearchTypes.indexTypes.PRODUCTS:
const productsTransformer =
this.config_.settings?.[SearchTypes.indexTypes.PRODUCTS]
?.transformer ?? transformProduct
return documents.map(productsTransformer)
default:
return documents
}
}
transformProducts(products) {
if (!products) {
return []
}
return products.map(transformProduct)
}
}
export default AlgoliaService
@@ -0,0 +1,18 @@
import { SearchTypes } from "@medusajs/types"
export type SearchOptions = {
paginationOptions: Record<string, unknown>
filter: string
additionalOptions: Record<string, unknown>
}
export type AlgoliaPluginOptions = {
applicationId: string
adminApiKey: string
/**
* Index settings
*/
settings?: {
[key: string]: SearchTypes.IndexSettings
}
}
@@ -1,42 +0,0 @@
const variantKeys = [
"sku",
"title",
"upc",
"ean",
"mid_code",
"hs_code",
"options",
]
const prefix = `variant`
export const transformProduct = (product) => {
const initialObj = variantKeys.reduce((obj, key) => {
obj[`${prefix}_${key}`] = []
return obj
}, {})
initialObj[`${prefix}_options_value`] = []
const flattenedVariantFields = product.variants.reduce((obj, variant) => {
variantKeys.forEach((k) => {
if (k === "options" && variant[k]) {
const values = variant[k].map((option) => option.value)
obj[`${prefix}_options_value`] =
obj[`${prefix}_options_value`].concat(values)
return
}
return variant[k] && obj[`${prefix}_${k}`].push(variant[k])
})
return obj
}, initialObj)
product.objectID = product.id
product.type_value = product.type && product.type.value
product.collection_title = product.collection && product.collection.title
product.collection_handle = product.collection && product.collection.handle
product.tags_value = product.tags ? product.tags.map((t) => t.value) : []
return {
...product,
...flattenedVariantFields,
}
}
@@ -0,0 +1,44 @@
import { variantKeys } from "@medusajs/types"
const prefix = `variant`
export const transformProduct = (product: any) => {
let transformedProduct = { ...product } as Record<string, unknown>
const initialObj = variantKeys.reduce((obj, key) => {
obj[`${prefix}_${key}`] = []
return obj
}, {})
initialObj[`${prefix}_options_value`] = []
const flattenedVariantFields = product.variants.reduce((obj, variant) => {
variantKeys.forEach((k) => {
if (k === "options" && variant[k]) {
const values = variant[k].map((option) => option.value)
obj[`${prefix}_options_value`] =
obj[`${prefix}_options_value`].concat(values)
return
}
return variant[k] && obj[`${prefix}_${k}`].push(variant[k])
})
return obj
}, initialObj)
transformedProduct.objectID = product.id
transformedProduct.type_value = product.type && product.type.value
transformedProduct.collection_title =
product.collection && product.collection.title
transformedProduct.collection_handle =
product.collection && product.collection.handle
transformedProduct.tags_value = product.tags
? product.tags.map((t) => t.value)
: []
transformedProduct.categories = (product?.categories || []).map((c) => c.name)
const prod = {
...transformedProduct,
...flattenedVariantFields,
}
return prod
}
@@ -0,0 +1,29 @@
{
"compilerOptions": {
"lib": ["es2020"],
"target": "es2020",
"outDir": "./dist",
"esModuleInterop": true,
"declaration": true,
"module": "commonjs",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"sourceMap": true,
"noImplicitReturns": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"noImplicitThis": true,
"allowJs": true,
"skipLibCheck": true,
"downlevelIteration": true // to use ES5 specific tooling
},
"include": ["src"],
"exclude": [
"dist",
"src/**/__tests__",
"src/**/__mocks__",
"src/**/__fixtures__",
"node_modules"
]
}
@@ -0,0 +1,5 @@
{
"extends": "./tsconfig.json",
"include": ["src"],
"exclude": ["node_modules"]
}