Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ jobs:
strategy:
matrix:
os: [ubuntu-latest]
node: [16]
node: [22]

steps:
- uses: actions/setup-node@v3
Expand All @@ -26,7 +26,7 @@ jobs:
uses: actions/checkout@master

- name: cache node_modules
uses: actions/cache@v2
uses: actions/cache@v4
with:
path: node_modules
key: ${{ matrix.os }}-node-v${{ matrix.node }}-deps-${{ hashFiles(format('{0}{1}', github.workspace, '/yarn.lock')) }}
Expand Down
12 changes: 0 additions & 12 deletions docs/content/1.getting-started/3.usage.md
Original file line number Diff line number Diff line change
Expand Up @@ -132,16 +132,4 @@ const algolia = useAlgoliaRef()
</script>
```

## `useAlgoliaInitIndex`

Use this composable to initialize index you would like to search through. It accepts an index name as a parameter

```vue
<script setup>
const algoliaIndex = useAlgoliaInitIndex('test')

console.log(algoliaIndex.appId)
</script>
```

For more details about initializing index check out the official documentation [here](https://www.algolia.com/doc/api-client/getting-started/instantiate-client-index/javascript/?client=javascript#initialize-an-index)
28 changes: 17 additions & 11 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@
}
},
"main": "./dist/module.cjs",
"types": "./dist/types.d.ts",
"files": [
"dist"
],
Expand All @@ -29,35 +28,39 @@
"dev": "nuxi dev playground",
"dev:build": "nuxi build playground",
"dev:preview": "nuxi preview playground",
"dev:prepare": "nuxt-module-build --stub && nuxt-module-build prepare && nuxi prepare playground",
"dev:prepare": "nuxt-module-build build --stub && nuxt-module-build prepare && nuxi prepare playground",
"docs": "cd docs && yarn dev",
"release": "nuxt-module-build && standard-version && git push --follow-tags && npm publish",
"release": "nuxt-module-build build && standard-version && git push --follow-tags && npm publish",
"lint": "eslint --ext .js,.ts,.vue"
},
"dependencies": {
"@algolia/cache-in-memory": "^4.14.2",
"@algolia/recommend": "^4.12.2",
"@algolia/requester-fetch": "^4.23.2",
"@algolia/requester-node-http": "^5.21.0",
"@algolia/cache-in-memory": "^4.26.0",
"@algolia/recommend": "^5.52.1",
"@algolia/requester-fetch": "^5.52.1",
"@algolia/requester-node-http": "^5.52.1",
"@nuxt/kit": "^3.7.0",
"algoliasearch": "^4.11.0",
"algoliasearch": "^5.52.1",
"defu": "^6.1.4",
"exsolve": "^1.0.4",
"instantsearch.css": "^7.4.5",
"metadata-scraper": "^0.2.49",
"mocked-exports": "^0.1.1",
"storyblok-algolia-indexer": "^1.1.0",
"vue-instantsearch": "^4.3.2"
"vue-instantsearch": "^4.26.3"
},
"devDependencies": {
"@docsearch/css": "^3.0.0",
"@docsearch/js": "^3.0.0",
"@nuxt/module-builder": "latest",
"@nuxt/cli": "^3.35.2",
"@nuxt/module-builder": "^1.0.2",
"@nuxtjs/eslint-config-typescript": "latest",
"eslint": "latest",
"nuxi": "^3.9.0",
"nuxt": "^3.16.0",
"standard-version": "^9.3.2",
"typescript": "^5.2.2"
"typescript": "^5.8.3",
"vite": "^6.0.0",
"vue": "^3.0.0"
},
"publishConfig": {
"access": "public"
Expand All @@ -75,5 +78,8 @@
"nuxt",
"module"
],
"engines": {
"node": ">=22.0.0"
},
"packageManager": "yarn@1.22.22+sha1.ac34549e6aa8e7ead463a7407e1c7390f61a6610"
}
2 changes: 1 addition & 1 deletion playground/nuxt.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,4 +42,4 @@ export default defineNuxtConfig({
},

compatibilityDate: '2025-03-19'
})
})
12 changes: 7 additions & 5 deletions playground/pages/index.vue
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,8 @@
</template>

<script lang="ts" setup>
import { useSeoMeta } from '#imports'
import { AisInstantSearch, AisSearchBox, AisHits } from 'vue-instantsearch/vue3/es'
import { useSeoMeta } from '#imports'
// Used to try the refresh of the component on options changes
const indexName = ref('test_index')

Expand All @@ -36,14 +36,14 @@ const algolia = useAlgoliaRef()
const { result: recommendResult, get } = useAlgoliaRecommend()

// Just add some indices in ./playground/types.d.ts, they should then be autocompleted here
const { search: typedSearch } = useAlgoliaInitIndex('test_index')
const { search: typedSearch, result: typedResult } = useAlgoliaSearch('test_index')

// SSR Searching for results
const { data } = await useAsyncData('ssr-search-results', () => search({ query: 'Samsung' }))

onMounted(async () => {
// useSearch
await search({ query: 'Samsung', requestOptions: { filters: 'objectID:ecommerce-sample-data-99' } })
await search({ query: 'Samsung', filters: 'objectID:ecommerce-sample-data-99' })

// useSearchForFacetValues
const facet = {
Expand All @@ -53,10 +53,12 @@ onMounted(async () => {
await searchForFacetValues({ facet })

// useAlgoliaRecommend
await get({ queries: [{ indexName: indexName.value, model: 'related-products', objectID: 'ecommerce-sample-data-99' }] })
await get({ requests: [{ indexName: indexName.value, model: 'related-products', objectID: 'ecommerce-sample-data-99', threshold: 0.5 }] })

// Notice the type of typedFoo is inferred from the type of the result of the call to useInitIndex
const typedFoo = await typedSearch('foo')
const typedFoo = await typedSearch({
query: 'foo'
})

// @ts-expect-error bar should be a number
typedFoo.hits[0].bar = '1'
Expand Down
2 changes: 1 addition & 1 deletion playground/types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import './../src/module'

declare module '../src/module' {
interface AlgoliaIndices {
coolIndex: {
test_index: {
foo: string
bar: number
}
Expand Down
19 changes: 9 additions & 10 deletions src/hooks/crawler.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@

import algoliasearch from 'algoliasearch'
import { algoliasearch } from 'algoliasearch'
import scraper from 'metadata-scraper'
import type { SearchClient, SearchIndex } from 'algoliasearch'
import type { SearchClient } from 'algoliasearch'
import type { MetaData } from 'metadata-scraper/lib/types'
import type { Nuxt } from '@nuxt/schema'
import type { ModuleOptions } from './../module'
Expand Down Expand Up @@ -108,24 +107,24 @@ export function createGenerateDoneHook (nuxt: Nuxt, options: ModuleOptions, page
if (pages.length > 0 && options.crawler) {
const { crawler: { apiKey, indexName }, applicationId } = options
const client = algoliasearch(applicationId, apiKey)
const index = client.initIndex(indexName)

await nuxt.callHook('crawler:index:before', {
options,
pages,
client,
index
indexName
})

await index.replaceAllObjects(pages, {
autoGenerateObjectIDIfNotExist: true
await client.replaceAllObjects({
indexName,
objects: pages.map(page => ({ ...page, objectID: page.href })),
})

await nuxt.callHook('crawler:index:after', {
options,
pages,
client,
index
indexName
})
}
}
Expand All @@ -134,8 +133,8 @@ export function createGenerateDoneHook (nuxt: Nuxt, options: ModuleOptions, page
export interface CrawlerHooks {
'crawler:add:before': (arg: { route: string, html: string, meta: MetaData, page: CrawlerPage }) => void
'crawler:add:after': (arg: { route: string, html: string, meta: MetaData, page: CrawlerPage }) => void
'crawler:index:before': (arg: { options: ModuleOptions, pages: CrawlerPage[], client: SearchClient, index: SearchIndex }) => void
'crawler:index:after': (arg: { options: ModuleOptions, pages: CrawlerPage[], client: SearchClient, index: SearchIndex }) => void
'crawler:index:before': (arg: { options: ModuleOptions, pages: CrawlerPage[], client: SearchClient, indexName: string }) => void
'crawler:index:after': (arg: { options: ModuleOptions, pages: CrawlerPage[], client: SearchClient, indexName: string }) => void
}

declare module '@nuxt/schema' {
Expand Down
5 changes: 2 additions & 3 deletions src/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ import { resolve } from 'path'
import { fileURLToPath } from 'url'
import { defineNuxtModule, addPlugin, addComponentsDir, addServerHandler, addImportsDir, useLogger, isNuxt2 } from '@nuxt/kit'
import { defu } from 'defu'
import { resolveModulePath } from 'exsolve'
import { createPageGenerateHook, createGenerateDoneHook } from './hooks'
import type { CrawlerPage, CrawlerHooks, CrawlerOptions } from './hooks'
import { InstantSearchThemes, type ModuleBaseOptions } from './types'
import { resolveModulePath } from 'exsolve'

const MODULE_NAME = '@nuxtjs/algolia'
const logger = useLogger(MODULE_NAME)
Expand All @@ -27,8 +27,7 @@ export default defineNuxtModule<ModuleOptions>({
name: '@nuxtjs/algolia',
configKey: 'algolia',
compatibility: {
nuxt: '>=3.0.0-rc.9 || ^2.16.0',
bridge: true
nuxt: '>=3.16.0'
}
},
defaults: {
Expand Down
15 changes: 12 additions & 3 deletions src/runtime/composables/useAlgoliaFacetedSearch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import { computed } from 'vue'
import type { SearchForFacetValuesResponse } from '@algolia/client-search'
import type { ComputedRef } from 'vue'
import type { AlgoliaIndices, RequestOptionsObject } from '../../types'
import { useAlgoliaInitIndex } from './useAlgoliaInitIndex'
import { useState } from '#imports'

export type SearchForFacetValuesParams = {
Expand All @@ -18,15 +17,25 @@ export type UseSearchForFacetValuesReturnType = {
search: (params: SearchForFacetValuesParams) => Promise<SearchForFacetValuesResponse>,
}

// @ts-expect-error TS can not infer string here
export function useAlgoliaFacetedSearch<K extends keyof AlgoliaIndices>(indexName: K): UseSearchForFacetValuesReturnType
export function useAlgoliaFacetedSearch(indexName: string): UseSearchForFacetValuesReturnType
export function useAlgoliaFacetedSearch (indexName: string) {
const algoliaIndex = useAlgoliaInitIndex(indexName)
const algolia = useAlgoliaRef()
const result = useState(`${indexName}-search-for-facet-values-result`, () => null)

const search = async ({ facet, requestOptions }: SearchForFacetValuesParams) => {
const { name, query } = facet
const searchForFacetValuesResult = await algoliaIndex.searchForFacetValues(name, query, requestOptions)
const searchForFacetValuesResult = await algolia.searchForFacets({
requests: [
{
indexName,
facet: name,
query,
type: 'facet'
}
]
}, requestOptions)
result.value = searchForFacetValuesResult
return searchForFacetValuesResult
}
Expand Down
14 changes: 0 additions & 14 deletions src/runtime/composables/useAlgoliaInitIndex.ts

This file was deleted.

24 changes: 12 additions & 12 deletions src/runtime/composables/useAlgoliaRecommend.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,18 @@
import type { RecommendationsQuery, RecommendClient } from '@algolia/recommend'
import type { RecommendationsRequest, RecommendClient } from '@algolia/recommend'
import { type ComputedRef, computed } from 'vue'
import type { RequestOptionsObject, SearchResponse } from '../../types'
import type { RequestOptionsObject } from '../../types'
import { useNuxtApp, useState } from '#imports'

export type RecommendParams = { queries: RecommendationsQuery[] } & RequestOptionsObject
export type RecommendParams = { requests: RecommendationsRequest[] } & RequestOptionsObject

export type MultipleQueriesResponse<T> = {
results: Array<SearchResponse<T>>;
}
export type RecommendResponse = Awaited<ReturnType<RecommendClient['getRecommendations']>>

export type UseAlgoliaRecommend<T> = {
result: ComputedRef<MultipleQueriesResponse<T>>;
get: (params: RecommendParams) => Promise<MultipleQueriesResponse<T>>
export type UseAlgoliaRecommend = {
result: ComputedRef<RecommendResponse | null>;
get: (params: RecommendParams) => Promise<RecommendResponse>
}

export function useAlgoliaRecommend<T> (key: string = ''): UseAlgoliaRecommend<T> {
export function useAlgoliaRecommend (key: string = ''): UseAlgoliaRecommend {
const { $algoliaRecommend } = useNuxtApp()
const algoliaRecommend: RecommendClient = $algoliaRecommend

Expand All @@ -24,8 +22,10 @@ export function useAlgoliaRecommend<T> (key: string = ''): UseAlgoliaRecommend<T

const result = useState(`recommend-result${key ? '-' + key : ''}`, () => null)

const get = async ({ queries, requestOptions }: RecommendParams) => {
result.value = await algoliaRecommend.getRecommendations<T>(queries, requestOptions)
const get = async ({ requests, requestOptions }: RecommendParams) => {
result.value = await algoliaRecommend.getRecommendations({
requests
}, requestOptions)

return result.value
}
Expand Down
5 changes: 2 additions & 3 deletions src/runtime/composables/useAlgoliaRef.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
import { SearchClient } from 'algoliasearch/lite'
import { useNuxtApp } from '#imports'

export const useAlgoliaRef = (): SearchClient => {
export const useAlgoliaRef = () => {
const nuxtApp = useNuxtApp()
const algolia: SearchClient = nuxtApp.$algolia
const algolia = nuxtApp.$algolia

return algolia
}
25 changes: 17 additions & 8 deletions src/runtime/composables/useAlgoliaSearch.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { computed, onUnmounted } from 'vue'
import type { SearchResponse } from '@algolia/client-search'
// import type { SearchResponses } from '@algolia/client-search'
import type { ComputedRef } from 'vue'
import type { BaseSearchParams, SearchResponse, SearchResponses } from 'algoliasearch'
import type { AlgoliaIndices, RequestOptionsObject } from '../../types'
import { useAlgoliaInitIndex } from './useAlgoliaInitIndex'
import { useState, useRuntimeConfig, useNuxtApp } from '#imports'

export type SearchParams = { query: string } & RequestOptionsObject;
export type SearchParams = BaseSearchParams & RequestOptionsObject;

export type UseSearchReturnType<T> = {
result: ComputedRef<SearchResponse<T>>,
Expand All @@ -14,22 +14,31 @@ export type UseSearchReturnType<T> = {

export function useAlgoliaSearch<K extends keyof AlgoliaIndices>(indexName?: K): UseSearchReturnType<AlgoliaIndices[K]>
export function useAlgoliaSearch<T>(indexName?: string): UseSearchReturnType<T>
export function useAlgoliaSearch (indexName?: string) {
export function useAlgoliaSearch<T> (indexName?: string) {
const config = useRuntimeConfig()
const index = indexName || config.public.algolia.globalIndex

if (!index) { throw new Error('`[@nuxtjs/algolia]` Cannot search in Algolia without `globalIndex` or `indexName` passed as a parameter') }

const algoliaIndex = useAlgoliaInitIndex(index)
const client = useAlgoliaRef()
const result = useState(`${index}-search-result`, () => null)

const search = async ({ query, requestOptions }: SearchParams) => {
const search = async ({ query, requestOptions, ...searchOptions }: SearchParams) => {
if (import.meta.server) {
const nuxtApp = useNuxtApp()
nuxtApp.$algolia.transporter.requester = (await import('@algolia/requester-fetch').then(lib => lib.default || lib)).createFetchRequester()
nuxtApp.$algolia.transporter.requester = (await import('@algolia/requester-fetch').then(lib => lib.createFetchRequester()))
}

const searchResult = await algoliaIndex.search(query, requestOptions)
const searchResults = await client.search<T>({
requests: [
{
indexName: index,
query,
...searchOptions
}
]
}, requestOptions)
const searchResult = searchResults.results[0]
result.value = searchResult
return searchResult
}
Expand Down
Loading
Loading