-
-
Notifications
You must be signed in to change notification settings - Fork 11.9k
Added snippets API hooks to the shared admin framework #30425
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
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
10a950c
Added snippets API hooks to the shared admin framework
9larsons ff6c9e0
Fixed snippet payload types and formats merging to match the API schema
9larsons d58d3de
Fixed snippet API contract and cache synchronization
9larsons 9638f9d
Fixed changeset ledger formatting check
9larsons File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,66 @@ | ||
| import { Meta, createMutation, createQuery } from '../utils/api/hooks'; | ||
|
|
||
| // mobiledoc and lexical travel as JSON strings on the wire; callers parse/stringify | ||
| export type Snippet = { | ||
| id: string; | ||
| name: string; | ||
| mobiledoc: string; | ||
| lexical: string | null; | ||
| created_at: string; | ||
| updated_at: string | null; | ||
| }; | ||
|
|
||
| // The add and edit schemas require name and mobiledoc on every item | ||
| export type SnippetEditableData = Pick<Snippet, 'name' | 'mobiledoc'> & | ||
| Partial<Pick<Snippet, 'lexical'>>; | ||
|
|
||
| export interface SnippetsResponseType { | ||
| meta?: Meta; | ||
| snippets: Snippet[]; | ||
| } | ||
|
|
||
| const dataType = 'SnippetsResponseType'; | ||
|
|
||
| // Without `formats` the API strips `lexical` from responses (mobiledoc is the default format) | ||
| const formats = 'mobiledoc,lexical'; | ||
|
|
||
| const useBrowseSnippetsQuery = createQuery<SnippetsResponseType>({ | ||
| dataType, | ||
| path: '/snippets/', | ||
| defaultSearchParams: { limit: 'all', formats }, | ||
| }); | ||
|
|
||
| export const useBrowseSnippets = ({ | ||
| searchParams, | ||
| ...args | ||
| }: Parameters<typeof useBrowseSnippetsQuery>[0] = {}) => | ||
| useBrowseSnippetsQuery({ | ||
| ...args, | ||
| // caller searchParams replace the defaults wholesale, so re-merge formats | ||
| searchParams: { limit: 'all', ...searchParams, formats }, | ||
| }); | ||
|
|
||
| export const useAddSnippet = createMutation<SnippetsResponseType, SnippetEditableData>({ | ||
| method: 'POST', | ||
| path: () => '/snippets/', | ||
| searchParams: () => ({ formats }), | ||
| body: (snippet) => ({ snippets: [snippet] }), | ||
| invalidateQueries: { dataType }, | ||
| }); | ||
|
|
||
| export const useEditSnippet = createMutation< | ||
| SnippetsResponseType, | ||
| SnippetEditableData & { id: string } | ||
| >({ | ||
| method: 'PUT', | ||
| path: ({ id }) => `/snippets/${id}/`, | ||
| searchParams: () => ({ formats }), | ||
| body: ({ id: _id, ...snippet }) => ({ snippets: [snippet] }), | ||
| invalidateQueries: { dataType }, | ||
| }); | ||
|
|
||
| export const useDeleteSnippet = createMutation<void, string>({ | ||
| method: 'DELETE', | ||
| path: (id) => `/snippets/${id}/`, | ||
| invalidateQueries: { dataType }, | ||
| }); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,183 @@ | ||
| import { act, waitFor } from '@testing-library/react'; | ||
| import { beforeEach, describe, expect, it, vi } from 'vitest'; | ||
| import { ValidationError } from '../../../src/utils/errors'; | ||
| import { renderHookWithProviders } from '../../../src/test/test-utils'; | ||
| import { | ||
| useAddSnippet, | ||
| useBrowseSnippets, | ||
| useDeleteSnippet, | ||
| useEditSnippet, | ||
| } from '../../../src/api/snippets'; | ||
| import { withMockFetch } from '../../utils/mock-fetch'; | ||
|
|
||
| const { mockSonnerError } = vi.hoisted(() => ({ | ||
| mockSonnerError: vi.fn(), | ||
| })); | ||
|
|
||
| vi.mock('sonner', () => ({ | ||
| toast: { | ||
| error: mockSonnerError, | ||
| dismiss: vi.fn(), | ||
| }, | ||
| })); | ||
|
|
||
| const existingSnippet = { | ||
| id: 'snippet-1', | ||
| name: 'Existing snippet', | ||
| mobiledoc: '{}', | ||
| lexical: '{"nodes":[]}', | ||
| created_at: '2024-01-01T00:00:00.000Z', | ||
| updated_at: '2024-01-01T00:00:00.000Z', | ||
| }; | ||
|
|
||
| const okResponse = (json: unknown) => ({ | ||
| json, | ||
| headers: { 'content-type': 'application/json' }, | ||
| ok: true, | ||
| status: 200, | ||
| }); | ||
|
|
||
| const duplicateSnippetResponse = { | ||
| errors: [ | ||
| { | ||
| code: 'VALIDATION', | ||
| context: 'Snippet already exists.', | ||
| details: null, | ||
| ghostErrorCode: null, | ||
| help: null, | ||
| id: 'snippet-error-id', | ||
| message: 'Validation error, cannot save snippet.', | ||
| property: null, | ||
| type: 'ValidationError', | ||
| }, | ||
| ], | ||
| }; | ||
|
|
||
| const mockErrorFetch = { | ||
| json: duplicateSnippetResponse, | ||
| headers: { 'content-type': 'application/json' }, | ||
| ok: false, | ||
| status: 422, | ||
| }; | ||
|
|
||
| const findCall = (mock: { calls: unknown[][] }, path: string) => | ||
| mock.calls.find((call) => String(call[0]).includes(path)); | ||
|
|
||
| describe('snippets api', () => { | ||
| beforeEach(() => { | ||
| vi.clearAllMocks(); | ||
| }); | ||
|
|
||
| it('browses all snippets in both formats', async () => { | ||
| await withMockFetch(okResponse({ snippets: [existingSnippet] }), async (mock) => { | ||
| const { result } = renderHookWithProviders(() => useBrowseSnippets()); | ||
|
|
||
| await waitFor(() => { | ||
| expect(result.current.data).toEqual({ snippets: [existingSnippet] }); | ||
| }); | ||
|
|
||
| const call = findCall(mock, '/snippets/'); | ||
| const url = new URL(String(call![0])); | ||
| expect(url.pathname).toBe('/ghost/api/admin/snippets/'); | ||
| expect(url.searchParams.get('limit')).toBe('all'); | ||
| expect(url.searchParams.get('formats')).toBe('mobiledoc,lexical'); | ||
| }); | ||
| }); | ||
|
|
||
| it('keeps the formats param when a caller passes its own search params', async () => { | ||
| await withMockFetch(okResponse({ snippets: [existingSnippet] }), async (mock) => { | ||
| const { result } = renderHookWithProviders(() => | ||
| useBrowseSnippets({ searchParams: { filter: 'name:foo' } }), | ||
| ); | ||
|
|
||
| await waitFor(() => { | ||
| expect(result.current.data).toEqual({ snippets: [existingSnippet] }); | ||
| }); | ||
|
|
||
| const url = new URL(String(findCall(mock, '/snippets/')![0])); | ||
| expect(url.searchParams.get('filter')).toBe('name:foo'); | ||
| expect(url.searchParams.get('limit')).toBe('all'); | ||
| expect(url.searchParams.get('formats')).toBe('mobiledoc,lexical'); | ||
| }); | ||
| }); | ||
|
|
||
| it('rejects duplicate creates with a validation error without reporting', async () => { | ||
| await withMockFetch(mockErrorFetch, async () => { | ||
| const { result } = renderHookWithProviders(() => useAddSnippet()); | ||
|
|
||
| await act(async () => { | ||
| await expect( | ||
| result.current.mutateAsync({ name: 'Existing snippet', mobiledoc: '{}' }), | ||
| ).rejects.toBeInstanceOf(ValidationError); | ||
| }); | ||
|
|
||
| expect(mockSonnerError).not.toHaveBeenCalled(); | ||
| }); | ||
| }); | ||
|
|
||
| it('adds a snippet and requests both formats back', async () => { | ||
| await withMockFetch(okResponse({ snippets: [existingSnippet] }), async (mock) => { | ||
| const { result } = renderHookWithProviders(() => useAddSnippet()); | ||
|
|
||
| await act(async () => { | ||
| await result.current.mutateAsync({ | ||
| name: 'Existing snippet', | ||
| lexical: '{"nodes":[]}', | ||
| mobiledoc: '{}', | ||
| }); | ||
| }); | ||
|
|
||
| const call = findCall(mock, '/snippets/')!; | ||
| const url = new URL(String(call[0])); | ||
| expect(url.pathname).toBe('/ghost/api/admin/snippets/'); | ||
| expect(url.searchParams.get('formats')).toBe('mobiledoc,lexical'); | ||
|
|
||
| const options = call[1] as RequestInit; | ||
| expect(options.method).toBe('POST'); | ||
| expect(JSON.parse(options.body as string)).toEqual({ | ||
| snippets: [{ name: 'Existing snippet', lexical: '{"nodes":[]}', mobiledoc: '{}' }], | ||
| }); | ||
| }); | ||
| }); | ||
|
|
||
| // The edit schema requires name and mobiledoc on every item, so edits send the full record | ||
| it('edits a snippet with the full record and requests both formats back', async () => { | ||
| await withMockFetch(okResponse({ snippets: [existingSnippet] }), async (mock) => { | ||
| const { result } = renderHookWithProviders(() => useEditSnippet()); | ||
|
|
||
| await act(async () => { | ||
| await result.current.mutateAsync({ | ||
| id: 'snippet-1', | ||
| name: 'Existing snippet', | ||
| mobiledoc: '{}', | ||
| lexical: '{"nodes":[]}', | ||
| }); | ||
| }); | ||
|
|
||
| const call = findCall(mock, '/snippets/snippet-1/')!; | ||
| const url = new URL(String(call[0])); | ||
| expect(url.pathname).toBe('/ghost/api/admin/snippets/snippet-1/'); | ||
| expect(url.searchParams.get('formats')).toBe('mobiledoc,lexical'); | ||
|
|
||
| const options = call[1] as RequestInit; | ||
| expect(options.method).toBe('PUT'); | ||
| expect(JSON.parse(options.body as string)).toEqual({ | ||
| snippets: [{ name: 'Existing snippet', mobiledoc: '{}', lexical: '{"nodes":[]}' }], | ||
| }); | ||
| }); | ||
| }); | ||
|
|
||
| it('deletes a snippet by id', async () => { | ||
| await withMockFetch({ ok: true, status: 204 }, async (mock) => { | ||
| const { result } = renderHookWithProviders(() => useDeleteSnippet()); | ||
|
|
||
| await act(async () => { | ||
| await result.current.mutateAsync('snippet-1'); | ||
| }); | ||
|
|
||
| const call = findCall(mock, '/snippets/snippet-1/')!; | ||
| expect(String(call[0])).toBe('http://localhost:3000/ghost/api/admin/snippets/snippet-1/'); | ||
| expect((call[1] as RequestInit).method).toBe('DELETE'); | ||
| }); | ||
| }); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy lift
🔎 Supported by static analysis
🏁 Script executed:
Repository: TryGhost/Ghost
Length of output: 27231
🏁 Script executed:
Repository: TryGhost/Ghost
Length of output: 15679
🏁 Script executed:
Repository: TryGhost/Ghost
Length of output: 10003
🏁 Script executed:
Repository: TryGhost/Ghost
Length of output: 3622
Validate snippet responses at the HTTP boundary.
useFetchApionly parses JSON. It does not validate the response shape, so malformed/snippets/data can reachuseBrowseSnippets,useAddSnippet, anduseEditSnippetasSnippetsResponseType.Add a Zod schema, derive
SnippetandSnippetsResponseTypewithz.infer, and parse these responses before consumers receive them. Add coverage for malformed responses.🤖 Prompt for AI Agents
Source: Path instructions