Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

POC for discussion #1

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 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
727 changes: 725 additions & 2 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 3 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,16 @@
"test:types": "vitest typecheck"
},
"dependencies": {
"lodash.isequal": "^4.5.0",
"vue": "^3.4.21"
},
"devDependencies": {
"@types/lodash.isequal": "^4.5.8",
"@vitejs/plugin-vue": "^5.0.4",
"typescript": "^5.2.2",
"vite": "^5.2.0",
"vite-plugin-dts": "^3.7.3",
"vitest": "^1.4.0",
"vue-tsc": "^2.0.6"
}
}
77 changes: 77 additions & 0 deletions src/createChannel.ts
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't implemented intervals or refreshing or anything like that. This is just cache a value based on queries existing.

Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { reactive, readonly, ref } from "vue";
import { Query, QueryAction, QueryOptions } from "./types";
import { sequence } from "./utils";

export type Channel<TAction extends QueryAction = any> = {
subscriptions: Map<number, QueryOptions>,
subscribe: (options?: QueryOptions) => Query<TAction>,
}

export function createChannel<TAction extends QueryAction>(action: TAction, parameters: Parameters<TAction>): Channel<TAction> {
const response = ref<Query<TAction>['response']>()
const error = ref<Query<TAction>['error']>()
const errored = ref<Query<TAction>['errored']>(false)
const executing = ref<Query<TAction>['executing']>(false)
const executed = ref<Query<TAction>['executed']>(false)

const subscriptions = new Map<number, QueryOptions>()
const { next: nextId } = sequence()

function execute(): void {
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Something to call out here. This isn't async. And I want to keep it that way so that when used with sync functions there isn't an automatic delay. I think we can update this to support async actions by using Promise functions.

executing.value = true

try {
response.value = action(parameters)
} catch(err) {
error.value = err
errored.value = true

return
} finally {
executed.value = true
executing.value = false
}

error.value = undefined
errored.value = false
}

function update(): void {
if(!executed.value) {
execute()
}
}

function addSubscription(options?: QueryOptions): () => void {
const id = nextId()

subscriptions.set(id, options ?? {})

update()

return () => {
subscriptions.delete(id)
update()
}
}

function subscribe(options?: QueryOptions): Query<TAction> {
const unsubscribe = addSubscription(options)

const query: Query<TAction> = readonly(reactive({
response,
error,
errored,
executing,
executed,
unsubscribe,
}))

return query
}

return {
subscriptions,
subscribe
}
}
64 changes: 64 additions & 0 deletions src/createManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { reactive, toRefs } from "vue";
import { Channel, createChannel } from "./createChannel";
import { CreateQueryOptions, Query, QueryAction, QueryOptions } from "./types";

export function createManager(options?: CreateQueryOptions) {
// might want to flatten this to a single map for simpler lookups
const channels = new Map<QueryAction, Map<string, Channel>>()

// should this be more elegant?
// this would break if there are function args I believe
function getParametersSignature(args: any[]): string {
return JSON.stringify(args)
}

function getChannel<
TAction extends QueryAction
>(action: TAction, parameters: Parameters<TAction>): Channel<TAction> {
if(!channels.has(action)) {
channels.set(action, new Map())
}

const actionChannels = channels.get(action)!
const argsString = getParametersSignature(parameters)

if(!actionChannels.has(argsString)) {
actionChannels.set(argsString, createChannel(action, parameters))
}

const channel = actionChannels.get(argsString)!

return channel
}

function deleteChannel<
TAction extends QueryAction
>(action: TAction, parameters: Parameters<TAction>): void {
const argsString = getParametersSignature(parameters)

channels.get(action)?.delete(argsString)
}

function subscribe<
TAction extends QueryAction
>(action: TAction, parameters: Parameters<TAction>, options?: QueryOptions): Query<TAction> {
const channel = getChannel(action, parameters)

const query = channel.subscribe(options)

return reactive({
...toRefs(query),
unsubscribe: () => {
query.unsubscribe()

if(channel.subscriptions.size === 0) {
deleteChannel(action, parameters)
}
}
})
Comment on lines +49 to +58
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is a pattern you'll see a couple times. You cannot spread a reactive object or you'll lose the reactivity. But you can call toRefs and spread that into a new reactive.

Using this so that I can add logic to the unsubscribe function at each level.

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is neat. Great find ❤️

}

return {
subscribe
}
}
13 changes: 13 additions & 0 deletions src/createQuery.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { test, expect, vi } from 'vitest'
import { createQuery } from './createQuery'

test('works', () => {
const action = vi.fn()
const { query } = createQuery()

query(action, [])
query(action, [])
query(action, [])

expect(action).toHaveBeenCalledOnce()
})
69 changes: 69 additions & 0 deletions src/createQuery.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import { computed, onScopeDispose, reactive, toRefs, toValue, watch } from "vue";
import { createManager } from "./createManager";
import { CreateQueryOptions, DisposableQuery, Query, QueryAction, QueryActionArgs, QueryOptions } from "./types";
import isEqual from 'lodash.isequal'
import { isDefined } from "./utilities";

export type QueryFunction = <TAction extends QueryAction>(action: TAction, args: Parameters<TAction>, options?: QueryOptions) => DisposableQuery<TAction>
export type QueryComposition = <TAction extends QueryAction>(action: TAction, args: QueryActionArgs<TAction>, options?: QueryOptions) => Query<TAction>

export type CreateQuery = {
query: QueryFunction,
useQuery: QueryComposition
}

const noop = () => undefined

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why do we need this? can't we just delay execute until we have args?


export function createQuery(options?: CreateQueryOptions): CreateQuery {
const manager = createManager(options)

const query: QueryFunction = (action, args, options) => {
const query = manager.subscribe(action, args, options)

return Object.assign(query, {
[Symbol.dispose]: () => {
query.unsubscribe()
},
Comment on lines +24 to +26
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this is all we need for dispose to work. But was getting build errors when testing. Might be too new for vite/vitest.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was able to get this working in 91cfc4c

})
}

const useQuery: QueryComposition = (action, parameters, options) => {
const value = query(noop, [])

watch(() => toValue(parameters), (parameters, previousParameters) => {
if(isDefined(previousParameters) && isEqual(previousParameters, parameters)) {
return
}

value.unsubscribe()

if(parameters === null) {
Object.assign(value, query(noop, []))
return
}

const newValue = query(action, parameters, options)

Object.assign(value, reactive({
...toRefs(newValue),
response: computed(() => {
if(newValue.executed) {
return newValue.response
}

return value.response
})
}))

}, { deep: true, immediate: true })

onScopeDispose(() => value.unsubscribe())

return value
}

return {
query,
useQuery,
}
}
11 changes: 11 additions & 0 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { createQuery } from './createQuery'

const { query, useQuery } = createQuery()

export {
query,
useQuery,
Comment on lines +5 to +7
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

library exports a default query and useQuery which is what I'd expect most implementations to use rather than actually calling createQuery

createQuery,
}

export * from './types'
31 changes: 31 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
type MaybeGetter<T> = T | Getter<T>
type Getter<T> = () => T
type MaybePromise<T> = T | Promise<T>

export type CreateQueryOptions = {
pauseActionsInBackground: boolean
}

export type QueryAction = (...args: any[]) => MaybePromise<any>

export type QueryActionArgs<TAction extends QueryAction> = MaybeGetter<Parameters<TAction>> | Getter<null>

export type QueryLifecycle = 'app' | 'route' | 'component'

export type QueryOptions = {
maxAge?: number,
lifecycle?: QueryLifecycle
}
Comment on lines +13 to +18
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non of this is implemented.


export type Query<TAction extends QueryAction> = {
response: ReturnType<TAction> | undefined,
error: unknown,
errored: boolean,
executed: boolean,
executing: boolean,
unsubscribe: () => void
}

export type DisposableQuery<TAction extends QueryAction> = Query<TAction> & {
[Symbol.dispose](): void;
}
3 changes: 3 additions & 0 deletions src/utilities.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export function isDefined<T>(value: T | undefined): value is T {
return typeof value !== 'undefined'
}
7 changes: 7 additions & 0 deletions src/utils.ts

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

utils.ts AND utilities.ts?

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would say they both need to be renamed lol, "utility" is just a dumping ground

Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export function sequence() {
let previous = 0

return {
next: () => previous += 1
}
}
4 changes: 2 additions & 2 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"lib": ["ES2020", "DOM", "DOM.Iterable", "esnext.disposable"],
"skipLibCheck": true,
"paths": { "@/*": ["./src/*"],},

Expand All @@ -20,6 +20,6 @@
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src/**/*.ts", "src/**/*.vue"],
"include": ["src/**/*.ts"],
"exclude": ["node_modules", "dist"]
}