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

refactor(core): stabilize studio usage of actions API #6783

Merged
merged 6 commits into from
May 29, 2024
Merged
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

This file was deleted.

Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import {delay} from 'rxjs/operators'
import {checkoutPair} from './checkoutPair'

const mockedDataRequest = jest.fn(() => of({}))
const mockedObservableRequest = jest.fn(() => of({}))
const mockedActionRequest = jest.fn(() => of({}))

const client = {
observable: {
Expand All @@ -16,19 +16,11 @@ const client = {
{_id: ids[0], _type: 'any', _rev: 'any'},
{_id: ids[1], _type: 'any', _rev: 'any'},
]),
action: mockedActionRequest,
},
dataRequest: mockedDataRequest,
}

const clientWithConfig = {
...client,
withConfig: () => ({
...client,
observable: {...client.observable, request: mockedObservableRequest},
}),
config: () => ({dataset: 'production'}),
}

const idPair = {publishedId: 'publishedId', draftId: 'draftId'}

beforeEach(() => {
Expand Down Expand Up @@ -223,48 +215,38 @@ describe('checkoutPair -- local actions', () => {

describe('checkoutPair -- server actions', () => {
test('patch', async () => {
const {draft, published} = checkoutPair(
clientWithConfig as any as SanityClient,
idPair,
of(true),
)
const {draft, published} = checkoutPair(client as any as SanityClient, idPair, of(true))
const combined = merge(draft.events, published.events)
const sub = combined.subscribe()
await new Promise((resolve) => setTimeout(resolve, 0))

draft.mutate(draft.patch([{set: {title: 'new title'}}]))
draft.commit()

expect(mockedObservableRequest).toHaveBeenCalledWith({
url: '/data/actions/production',
method: 'post',
tag: 'document.commit',
body: {
transactionId: expect.any(String),
actions: [
{
actionType: 'sanity.action.document.edit',
draftId: 'draftId',
publishedId: 'publishedId',
patch: {
set: {
title: 'new title',
},
expect(mockedActionRequest).toHaveBeenCalledWith(
[
{
actionType: 'sanity.action.document.edit',
draftId: 'draftId',
publishedId: 'publishedId',
patch: {
set: {
title: 'new title',
},
},
],
},
],
{
tag: 'document.commit',
transactionId: expect.any(String),
},
})
)

sub.unsubscribe()
})

test('published patch uses mutation endpoint', async () => {
const {draft, published} = checkoutPair(
clientWithConfig as any as SanityClient,
idPair,
of(true),
)
const {draft, published} = checkoutPair(client as any as SanityClient, idPair, of(true))
const combined = merge(draft.events, published.events)
const sub = combined.subscribe()
await new Promise((resolve) => setTimeout(resolve, 0))
Expand All @@ -273,7 +255,7 @@ describe('checkoutPair -- server actions', () => {
published.mutate(published.patch([{set: {title: 'new title'}}]))
published.commit()

expect(mockedObservableRequest).not.toHaveBeenCalled()
expect(mockedActionRequest).not.toHaveBeenCalled()

expect(mockedDataRequest).toHaveBeenCalledWith(
'mutate',
Expand All @@ -293,11 +275,7 @@ describe('checkoutPair -- server actions', () => {
})

test('create', async () => {
const {draft, published} = checkoutPair(
clientWithConfig as any as SanityClient,
idPair,
of(true),
)
const {draft, published} = checkoutPair(client as any as SanityClient, idPair, of(true))
const combined = merge(draft.events, published.events)
const sub = combined.subscribe()
await new Promise((resolve) => setTimeout(resolve, 0))
Expand All @@ -313,36 +291,30 @@ describe('checkoutPair -- server actions', () => {
])
draft.commit()

expect(mockedObservableRequest).toHaveBeenCalledWith({
url: '/data/actions/production',
method: 'post',
tag: 'document.commit',
body: {
transactionId: expect.any(String),
actions: [
{
actionType: 'sanity.action.document.create',
publishedId: 'publishedId',
attributes: {
_id: 'draftId',
_type: 'any',
_createdAt: 'now',
},
ifExists: 'fail',
expect(mockedActionRequest).toHaveBeenCalledWith(
[
{
actionType: 'sanity.action.document.create',
publishedId: 'publishedId',
attributes: {
_id: 'draftId',
_type: 'any',
_createdAt: 'now',
},
],
ifExists: 'fail',
},
],
{
tag: 'document.commit',
transactionId: expect.any(String),
},
})
)

sub.unsubscribe()
})

test('createIfNotExists', async () => {
const {draft, published} = checkoutPair(
clientWithConfig as any as SanityClient,
idPair,
of(true),
)
const {draft, published} = checkoutPair(client as any as SanityClient, idPair, of(true))
const combined = merge(draft.events, published.events)
const sub = combined.subscribe()
await new Promise((resolve) => setTimeout(resolve, 0))
Expand All @@ -358,14 +330,9 @@ describe('checkoutPair -- server actions', () => {
])
draft.commit()

expect(mockedObservableRequest).toHaveBeenCalledWith({
url: '/data/actions/production',
method: 'post',
expect(mockedActionRequest).toHaveBeenCalledWith([], {
tag: 'document.commit',
body: {
transactionId: expect.any(String),
actions: [],
},
transactionId: expect.any(String),
})

sub.unsubscribe()
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {type SanityClient} from '@sanity/client'
import {type Action, type SanityClient} from '@sanity/client'
import {type Mutation} from '@sanity/mutator'
import {type SanityDocument} from '@sanity/types'
import {omit} from 'lodash'
Expand All @@ -14,7 +14,6 @@ import {
} from '../buffered-doc'
import {getPairListener, type ListenerEvent} from '../getPairListener'
import {type IdPair, type PendingMutationsEvent, type ReconnectEvent} from '../types'
import {type HttpAction} from './actionTypes'

const isMutationEventForDocId =
(id: string) =>
Expand Down Expand Up @@ -95,12 +94,8 @@ function isLiveEditMutation(mutationParams: Mutation['params'], publishedId: str
return patchTargets.every((target) => target === publishedId)
}

function toActions(idPair: IdPair, mutationParams: Mutation['params']) {
return mutationParams.mutations.flatMap<HttpAction>((mutations) => {
if (Object.keys(mutations).length > 1) {
// todo: this might be a bit too strict, but I'm (lazily) trying to check if we ever get more than one mutation in a payload
throw new Error('Did not expect multiple mutations in the same payload')
}
function toActions(idPair: IdPair, mutationParams: Mutation['params']): Action[] {
return mutationParams.mutations.flatMap((mutations) => {
// This action is not always interoperable with the equivalent mutation. It will fail if the
// published version of the document already exists.
if (mutations.createIfNotExists) {
Expand All @@ -125,30 +120,18 @@ function toActions(idPair: IdPair, mutationParams: Mutation['params']) {
patch: omit(mutations.patch, 'id'),
}
}
throw new Error('Todo: implement')
throw new Error('Cannot map mutation to action')
})
}

function commitActions(
defaultClient: SanityClient,
idPair: IdPair,
mutationParams: Mutation['params'],
) {
function commitActions(client: SanityClient, idPair: IdPair, mutationParams: Mutation['params']) {
if (isLiveEditMutation(mutationParams, idPair.publishedId)) {
return commitMutations(defaultClient, mutationParams)
return commitMutations(client, mutationParams)
}

const vXClient = defaultClient.withConfig({apiVersion: 'X'})
const {dataset} = defaultClient.config()

return vXClient.observable.request({
url: `/data/actions/${dataset}`,
method: 'post',
return client.observable.action(toActions(idPair, mutationParams), {
tag: 'document.commit',
body: {
transactionId: mutationParams.transactionId,
actions: toActions(idPair, mutationParams),
},
transactionId: mutationParams.transactionId,
})
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ exports[`publish execute calls createOrReplace with _revision_lock_pseudo_field_
Object {
"listen": Array [],
"observable": Object {
"action": Array [],
"fetch": Array [],
"getDocuments": Array [],
"listen": Array [],
Expand Down Expand Up @@ -59,6 +60,7 @@ exports[`publish execute removes the \`_updatedAt\` field 1`] = `
Object {
"listen": Array [],
"observable": Object {
"action": Array [],
"fetch": Array [],
"getDocuments": Array [],
"listen": Array [],
Expand Down Expand Up @@ -104,6 +106,7 @@ exports[`publish execute takes in any and strengthens references where _strength
Object {
"listen": Array [],
"observable": Object {
"action": Array [],
"fetch": Array [],
"getDocuments": Array [],
"listen": Array [],
Expand Down
Loading
Loading