Skip to content

Commit

Permalink
feat!: upgrade to vue 3
Browse files Browse the repository at this point in the history
resolves #498
  • Loading branch information
danielroe committed Aug 29, 2024
1 parent 36c9b5b commit f498160
Show file tree
Hide file tree
Showing 10 changed files with 114 additions and 253 deletions.
4 changes: 1 addition & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<h1 align="center">🟢 vue-sanity</h1>
<p align="center">Sanity integration for VueJS</p>
<p align="center">Sanity integration for Vue</p>

<p align="center">
<a href="https://npmjs.com/package/vue-sanity">
Expand Down Expand Up @@ -34,8 +34,6 @@

## Quick Start

> If you are using Vue 2, then this project requires you be on at least Vue 2.7.
First install `vue-sanity`:

```bash
Expand Down
10 changes: 4 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@
"test:types": "tsc --noEmit"
},
"peerDependencies": {
"vue": "^2.7.0 || >=3.0.0-rc.0"
"vue": "^3.0.0"
},
"dependencies": {
"@sanity/client": "^6.21.3",
Expand All @@ -59,13 +59,13 @@
"@typescript-eslint/parser": "8.3.0",
"@vitest/coverage-v8": "2.0.5",
"@vue/composition-api": "1.7.2",
"@vue/test-utils": "1.3.6",
"@vue/test-utils": "2.4.6",
"bumpp": "^9.5.2",
"conventional-changelog-conventionalcommits": "8.0.0",
"eslint": "9.9.1",
"expect-type": "0.20.0",
"flush-promises": "1.0.2",
"happy-dom": "15.4.2",
"happy-dom": "15.5.0",
"husky": "9.1.5",
"lint-staged": "15.2.9",
"memory-fs": "0.5.0",
Expand All @@ -74,9 +74,7 @@
"unbuild": "2.0.0",
"vite": "5.4.2",
"vitest": "2.0.5",
"vue": "2.7.16",
"vue-server-renderer": "2.7.16",
"vue-template-compiler": "2.7.16"
"vue": "3.4.38"
},
"resolutions": {
"minimist": ">=1.2.8"
Expand Down
291 changes: 84 additions & 207 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

16 changes: 6 additions & 10 deletions src/cache.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import process from 'node:process'
import type { Ref } from 'vue'
import { computed, getCurrentInstance, isRef, onServerPrefetch, reactive, set, unref, watch } from 'vue'
import { computed, getCurrentInstance, isRef, onServerPrefetch, reactive, unref, useSSRContext, watch } from 'vue'

/**
* Cached data, status of fetch, timestamp of last fetch, error
*/
type CacheEntry<T> = [T, FetchStatus, number, any, Promise<T>]
type CacheEntry<T> = [T, FetchStatus, number, any, Promise<T> | null]

const cache = reactive<Record<string, CacheEntry<any>>>({})

Expand All @@ -19,7 +19,7 @@ export function ensureInstance() {
export function getServerInstance() {
const instance = getCurrentInstance()

if (process.env.VITE_SSG || instance?.proxy.$isServer)
if (process.env.VITE_SSG || (import.meta as any).env?.SSR || (import.meta as any).server)
return instance?.proxy
return false
}
Expand Down Expand Up @@ -83,7 +83,7 @@ export function useCache<T, K = null>(
status = 'initialised',
time = new Date().getTime(),
}: SetCacheOptions<T, K>) {
set(cache, key, [value, status, time, error])
cache[key] = [value, status, time, error, null]
}

const serverInstance = getServerInstance()
Expand Down Expand Up @@ -123,11 +123,7 @@ export function useCache<T, K = null>(
if (!(key in cache))
initialiseCache({ key, value, status })

set(cache[key], 0, value)
set(cache[key], 1, status)
set(cache[key], 2, new Date().getTime())
set(cache[key], 3, error)
set(cache[key], 4, promise)
cache[key] = [value, status, new Date().getTime(), error, promise]
}

function fetch(query = unref(key), force?: boolean) {
Expand Down Expand Up @@ -164,7 +160,7 @@ export function useCache<T, K = null>(
}

if (enableSSR && serverInstance) {
const ctx = serverInstance.$ssrContext
const ctx = useSSRContext()
if (ctx) {
if (ctx.nuxt && !ctx.nuxt.vsanity) {
ctx.nuxt.vsanity = {}
Expand Down
2 changes: 1 addition & 1 deletion test/__snapshots__/ssr.spec.ts.snap
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`ssr > cache fetches data correctly on SSR 1`] = `"<div data-server-rendered="true">data: value, status: server loaded</div>"`;
exports[`ssr > cache fetches data correctly on SSR 1`] = `"<div>data: value, status: server loaded</div>"`;
12 changes: 4 additions & 8 deletions test/helpers/mount.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,9 @@
import Vue, { h } from 'vue'
import type { Data, SetupFunction } from 'vue'
import { h } from 'vue'
import { mount } from '@vue/test-utils'
import flushPromises from 'flush-promises'

Vue.config.productionTip = false
Vue.config.devtools = false

export async function runInSetup<T extends SetupFunction<Data, Data>, D extends SetupFunction<Data, Data>>(setup: T, child?: D) {
let result
export async function runInSetup<T extends () => unknown, D extends () => unknown>(setup: T, child?: D) {
let result: T & D
mount({
setup() {
result = (setup as any)() || {}
Expand All @@ -23,5 +19,5 @@ export async function runInSetup<T extends SetupFunction<Data, Data>, D extends

await flushPromises()

return result as ReturnType<T> & ReturnType<D>
return result! as ReturnType<T> & ReturnType<D>
}
4 changes: 2 additions & 2 deletions test/image.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ const config = {
apiVersion: '2021-03-25',
} satisfies ClientConfig

;(globalThis.console.error as any) = vi.fn()
;(globalThis.console.warn as any) = vi.fn()

describe('image builder', () => {
const image = {
Expand All @@ -37,7 +37,7 @@ describe('image builder', () => {
})

expect(error).toBeDefined()
expect(console.error).toBeCalled()
expect(console.warn).toBeCalled()
})

it('errors when run outside of setup', async () => {
Expand Down
5 changes: 0 additions & 5 deletions test/index.spec.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import Vue from 'vue'

import { beforeEach, describe, expect, it, vi } from 'vitest'
import { createClient } from '@sanity/client'

import { useSanityClient } from '../src'
import { runInSetup } from './helpers/mount'

Vue.config.productionTip = false
Vue.config.devtools = false

vi.mock('@sanity/client')
;(globalThis.console.error as any) = vi.fn()

Expand Down
12 changes: 8 additions & 4 deletions test/query.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ const config = {
}

const mockFetch = vi.fn(async (key: string) => `return value-${key}`)
;(globalThis.console.error as any) = vi.fn()
;(globalThis.console.warn as any) = vi.fn()

const mockUnsubscribe = vi.fn()
const mockSubscribe = vi.fn((callback: (result: any) => void) => {
Expand All @@ -39,7 +39,7 @@ vi.mock('@sanity/client', () => {

beforeEach(() => {
createClient.mockClear()
;(globalThis.console.error as any).mockClear()
;(globalThis.console.warn as any).mockClear()
mockListen.mockClear()
mockSubscribe.mockClear()
mockUnsubscribe.mockClear()
Expand All @@ -58,14 +58,18 @@ describe('fetcher', () => {
expect(error).toBeDefined()
})
it('errors when client is not injected', async () => {
let error
await runInSetup(() => {
try {
useSanityFetcher(() => `my-error`)
}
catch {}
catch (e) {
error = e
}
})

expect(console.error).toBeCalled()
expect(console.warn).toBeCalled()
expect(error).toBeDefined()
})

it('allows default options to be set', async () => {
Expand Down
11 changes: 4 additions & 7 deletions test/ssr.spec.ts
Original file line number Diff line number Diff line change
@@ -1,26 +1,23 @@
/** @vitest-environment node */
import Vue, { h, ref } from 'vue'
import { createRenderer } from 'vue-server-renderer'
import { createApp, h, ref } from 'vue'
import { renderToString } from 'vue/server-renderer'

import { describe, expect, it } from 'vitest'

import { useCache } from '../src/cache'
import { fetcher } from './helpers/utils'

Vue.config.productionTip = false
Vue.config.devtools = false

describe('ssr', () => {
it('cache fetches data correctly on SSR', async () => {
const app = new Vue({
const app = createApp({
setup() {
const { data, status } = useCache(ref('key'), () => fetcher('value'))

return () =>
h('div', {}, [`data: ${data.value}, status: ${status.value}`])
},
})
const html = await createRenderer().renderToString(app)
const html = await renderToString(app)
expect(html).toMatchSnapshot()
})
}, 10000)

0 comments on commit f498160

Please sign in to comment.