Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

chore: Remove ProjectContent mobx store (#18044)

Ivan Vasilov5ac5e20fd830
diff --git a/studio/__mocks__/hooks.js b/studio/__mocks__/hooks.js
index e5fbfee3462..1c64da8e2d2 100644
--- a/studio/__mocks__/hooks.js
+++ b/studio/__mocks__/hooks.js
@@ -6,6 +6,8 @@ export const useStore = _useStore
export const useParams = jest.fn().mockImplementation(() => ({ ref: '123' }))
+export const useLocalStorage = jest.fn().mockImplementation(() => [[], jest.fn()])
+
// mocks browser event listener adding/removing
window.matchMedia = jest.fn().mockReturnValue({
removeEventListener: jest.fn(),
diff --git a/studio/data/content/content-insert-mutation.ts b/studio/data/content/content-insert-mutation.ts
new file mode 100644
index 00000000000..bdda41f9471
--- /dev/null
+++ b/studio/data/content/content-insert-mutation.ts
@@ -0,0 +1,63 @@
+import { useMutation, UseMutationOptions, useQueryClient } from '@tanstack/react-query'
+
+import { components } from 'data/api'
+import { post } from 'data/fetchers'
+import { Content } from './content-query'
+import { contentKeys } from './keys'
+
+export type InsertContentPayload = Omit<components['schemas']['CreateContentParams'], 'content'> & {
+ content: Content['content']
+}
+
+export type InsertContentVariables = {
+ projectRef: string
+ payload: InsertContentPayload
+}
+
+export async function insertContent(
+ { projectRef, payload }: InsertContentVariables,
+ signal?: AbortSignal
+) {
+ const { data, error } = await post('/platform/projects/{ref}/content', {
+ params: { path: { ref: projectRef } },
+ body: {
+ id: payload.id,
+ name: payload.name,
+ description: payload.description,
+ owner_id: payload.owner_id,
+ type: payload.type,
+ visibility: payload.visibility,
+ content: payload.content as any,
+ },
+ signal,
+ })
+ if (error) throw error
+
+ return data
+}
+
+export type InsertContentData = Awaited<ReturnType<typeof insertContent>>
+
+export const useContentInsertMutation = ({
+ onSuccess,
+ ...options
+}: Omit<
+ UseMutationOptions<InsertContentData, unknown, InsertContentVariables>,
+ 'mutationFn'
+> = {}) => {
+ const queryClient = useQueryClient()
+
+ return useMutation<InsertContentData, unknown, InsertContentVariables>(
+ (args) => insertContent(args),
+ {
+ async onSuccess(data, variables, context) {
+ const { projectRef } = variables
+
+ await Promise.all([queryClient.invalidateQueries(contentKeys.list(projectRef))])
+
+ await onSuccess?.(data, variables, context)
+ },
+ ...options,
+ }
+ )
+}
diff --git a/studio/pages/_app.tsx b/studio/pages/_app.tsx
index 81053a44023..999c9105603 100644
--- a/studio/pages/_app.tsx
+++ b/studio/pages/_app.tsx
@@ -42,6 +42,10 @@ import {
CommandMenuWrapper,
RouteValidationWrapper,
} from 'components/interfaces/App'
+import {
+ FeaturePreviewContextProvider,
+ FeaturePreviewModal,
+} from 'components/interfaces/App/FeaturePreview'
import FlagProvider from 'components/ui/Flag/FlagProvider'
import PageTelemetry from 'components/ui/PageTelemetry'
import { useRootQueryClient } from 'data/query-client'
@@ -55,10 +59,6 @@ import { useAppStateSnapshot } from 'state/app-state'
import { RootStore } from 'stores'
import HCaptchaLoadedStore from 'stores/hcaptcha-loaded-store'
import { AppPropsWithLayout } from 'types'
-import {
- FeaturePreviewContextProvider,
- FeaturePreviewModal,
-} from 'components/interfaces/App/FeaturePreview'
dayjs.extend(customParseFormat)
dayjs.extend(utc)
@@ -105,8 +105,6 @@ function CustomApp({ Component, pageProps }: AppPropsWithLayout) {
: undefined
)
- const getSavingState = () => rootStore.content.savingState
-
useEffect(() => {
// Check for telemetry consent
if (typeof window !== 'undefined') {
@@ -132,25 +130,6 @@ function CustomApp({ Component, pageProps }: AppPropsWithLayout) {
)
}
}
-
- // prompt the user if they try and leave with unsaved content store changes
- const warningText = 'You have unsaved changes - are you sure you wish to leave this page?'
-
- const handleWindowClose = (e: BeforeUnloadEvent) => {
- const savingState = getSavingState()
- const unsavedChanges =
- savingState === 'UPDATING_REQUIRED' ||
- savingState === 'UPDATING' ||
- savingState === 'UPDATING_FAILED'
-
- if (!unsavedChanges) return
- e.preventDefault()
- return (e.returnValue = warningText)
- }
-
- window.addEventListener('beforeunload', handleWindowClose)
-
- return () => window.removeEventListener('beforeunload', handleWindowClose)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
diff --git a/studio/pages/project/[ref]/logs/explorer/index.tsx b/studio/pages/project/[ref]/logs/explorer/index.tsx
index 32e873816c6..8a24e4d4dcd 100644
--- a/studio/pages/project/[ref]/logs/explorer/index.tsx
+++ b/studio/pages/project/[ref]/logs/explorer/index.tsx
@@ -1,18 +1,10 @@
import dayjs from 'dayjs'
-import { useEffect, useState } from 'react'
-import { useRouter } from 'next/router'
import { observer } from 'mobx-react-lite'
-import { Input, Modal, Form, Button } from 'ui'
+import { useRouter } from 'next/router'
+import { useEffect, useState } from 'react'
+import { Button, Form, Input, Modal } from 'ui'
-import { useStore } from 'hooks'
import { useParams } from 'common/hooks'
-import useLogsQuery from 'hooks/analytics/useLogsQuery'
-import { NextPageWithLayout, UserContent } from 'types'
-import { uuidv4 } from 'lib/helpers'
-import { LogsLayout } from 'components/layouts'
-import CodeEditor from 'components/ui/CodeEditor'
-import ShimmerLine from 'components/ui/ShimmerLine'
-import LoadingOpacity from 'components/ui/LoadingOpacity'
import {
DatePickerToFrom,
LogsQueryPanel,
@@ -25,16 +17,25 @@ import {
TEMPLATES,
useEditorHints,
} from 'components/interfaces/Settings/Logs'
-import { useUpgradePrompt } from 'hooks/misc/useUpgradePrompt'
import UpgradePrompt from 'components/interfaces/Settings/Logs/UpgradePrompt'
+import { LogsLayout } from 'components/layouts'
+import CodeEditor from 'components/ui/CodeEditor'
+import LoadingOpacity from 'components/ui/LoadingOpacity'
import LogsExplorerHeader from 'components/ui/Logs/LogsExplorerHeader'
+import ShimmerLine from 'components/ui/ShimmerLine'
+import { useContentInsertMutation } from 'data/content/content-insert-mutation'
import { useProjectSubscriptionV2Query } from 'data/subscriptions/project-subscription-v2-query'
+import { useLocalStorage, useStore } from 'hooks'
+import useLogsQuery from 'hooks/analytics/useLogsQuery'
+import { useUpgradePrompt } from 'hooks/misc/useUpgradePrompt'
+import { uuidv4 } from 'lib/helpers'
+import { LogSqlSnippets, NextPageWithLayout } from 'types'
const PLACEHOLDER_QUERY =
'select\n cast(timestamp as datetime) as timestamp,\n event_message, metadata \nfrom edge_logs \nlimit 5'
export const LogsExplorerPage: NextPageWithLayout = () => {
useEditorHints()
- const { ui, content } = useStore()
+ const { ui } = useStore()
const router = useRouter()
const { ref: projectRef, q, ite, its } = useParams()
const [editorId, setEditorId] = useState<string>(uuidv4())
@@ -49,6 +50,19 @@ export const LogsExplorerPage: NextPageWithLayout = () => {
iso_timestamp_end: ite ? (ite as string) : undefined,
}
)
+ const [recentLogs, setRecentLogs] = useLocalStorage<LogSqlSnippets.Content[]>(
+ `project-content-${projectRef}-recent-log-sql`,
+ []
+ )
+ const addRecentLogSqlSnippet = (snippet: Partial<LogSqlSnippets.Content>) => {
+ const defaults: LogSqlSnippets.Content = {
+ schema_version: '1',
+ favorite: false,
+ sql: '',
+ content_id: '',
+ }
+ setRecentLogs([...recentLogs, { ...defaults, ...snippet }])
+ }
const { showUpgradePrompt, setShowUpgradePrompt } = useUpgradePrompt(
params.iso_timestamp_start as string
@@ -97,9 +111,7 @@ export const LogsExplorerPage: NextPageWithLayout = () => {
pathname: router.pathname,
query: { ...router.query, q: template.searchString },
})
- content.addRecentLogSqlSnippet({
- sql: template.searchString,
- })
+ addRecentLogSqlSnippet({ sql: template.searchString })
}
const handleRun = (value?: string | React.MouseEvent<HTMLButtonElement>) => {
@@ -113,9 +125,7 @@ export const LogsExplorerPage: NextPageWithLayout = () => {
pathname: router.pathname,
query: { ...router.query, q: query },
})
- content.addRecentLogSqlSnippet({
- sql: query,
- })
+ addRecentLogSqlSnippet({ sql: query })
}
const handleClear = () => {
@@ -151,6 +161,26 @@ export const LogsExplorerPage: NextPageWithLayout = () => {
}
}
+ const { isLoading: isSubmitting, mutate: createContent } = useContentInsertMutation({
+ onError: (e) => {
+ const error = e as { message: string }
+ console.error(error)
+ setSaveModalOpen(false)
+ ui.setNotification({
+ error,
+ category: 'error',
+ message: `Failed to save query: ${error.message}`,
+ })
+ },
+ onSuccess: (values) => {
+ setSaveModalOpen(false)
+ ui.setNotification({
+ category: 'success',
+ message: `Saved "${values[0].name}" log query`,
+ })
+ },
+ })
+
return (
<div className="w-full h-full px-5 py-6 mx-auto">
<LogsExplorerHeader />
@@ -213,41 +243,24 @@ export const LogsExplorerPage: NextPageWithLayout = () => {
onSubmit={async (values: any, { setSubmitting }: any) => {
setSubmitting(true)
- const payload: UserContent = {
+ const payload = {
+ id: uuidv4(),
name: values.name,
description: values.description || '',
- type: 'log_sql',
+ type: 'log_sql' as const,
content: {
content_id: editorId,
sql: editorValue,
schema_version: '1',
favorite: false,
},
- visibility: 'user',
+ visibility: 'user' as const,
}
- try {
- const { data: query, error } = await content.create(payload)
- if (error) throw error
- setSubmitting(false)
- setSaveModalOpen(false)
- ui.setNotification({
- category: 'success',
- message: `Saved "${values.name}" log query`,
- })
- } catch (error: any) {
- console.error(error)
- setSubmitting(false)
- setSaveModalOpen(false)
- ui.setNotification({
- error,
- category: 'error',
- message: `Failed to save query: ${error.message}`,
- })
- }
+ createContent({ projectRef: projectRef!, payload })
}}
>
- {({ isSubmitting }: any) => (
+ {() => (
<>
<div className="py-4">
<Modal.Content>
diff --git a/studio/pages/project/[ref]/logs/explorer/recent.tsx b/studio/pages/project/[ref]/logs/explorer/recent.tsx
index 2e2d3c06695..bd7645e5e1f 100644
--- a/studio/pages/project/[ref]/logs/explorer/recent.tsx
+++ b/studio/pages/project/[ref]/logs/explorer/recent.tsx
@@ -1,24 +1,23 @@
import { observer } from 'mobx-react-lite'
import Link from 'next/link'
-import { useEffect } from 'react'
import { useParams } from 'common'
import RecentQueriesItem from 'components/interfaces/Settings/Logs/RecentQueriesItem'
import LogsLayout from 'components/layouts/LogsLayout/LogsLayout'
import Table from 'components/to-be-cleaned/Table'
import LogsExplorerHeader from 'components/ui/Logs/LogsExplorerHeader'
-import { useStore } from 'hooks'
+import { useLocalStorage } from 'hooks'
import { LogSqlSnippets, NextPageWithLayout } from 'types'
import { Button, IconClock } from 'ui'
export const LogsSavedPage: NextPageWithLayout = () => {
- const { content } = useStore()
const { ref } = useParams()
- useEffect(() => {
- content.loadPersistentData()
- }, [ref])
- const recent = content.recentLogSqlSnippets.slice().reverse()
+ const [recentLogSnippets, setRecentLogSnippets] = useLocalStorage<LogSqlSnippets.Content[]>(
+ `project-content-${ref}-recent-log-sql`,
+ []
+ )
+ const recent = recentLogSnippets.slice().reverse()
return (
<div className="mx-auto w-full px-5 py-6 h-full">
@@ -29,13 +28,7 @@ export const LogsSavedPage: NextPageWithLayout = () => {
<>
<Table.th>Snippets</Table.th>
<Table.th className="w-24">
- <Button
- size="tiny"
- type="default"
- onClick={() => {
- content.clearRecentLogSqlSnippets()
- }}
- >
+ <Button size="tiny" type="default" onClick={() => setRecentLogSnippets([])}>
Clear history
</Button>
</Table.th>
diff --git a/studio/pages/project/[ref]/logs/explorer/saved.tsx b/studio/pages/project/[ref]/logs/explorer/saved.tsx
index b40313517ea..30f443134ee 100644
--- a/studio/pages/project/[ref]/logs/explorer/saved.tsx
+++ b/studio/pages/project/[ref]/logs/explorer/saved.tsx
@@ -1,28 +1,27 @@
import { observer } from 'mobx-react-lite'
import Link from 'next/link'
-import { useEffect } from 'react'
import { useParams } from 'common'
import { LogsSavedQueriesItem } from 'components/interfaces/Settings/Logs'
import { LogsLayout } from 'components/layouts'
import Table from 'components/to-be-cleaned/Table'
import LogsExplorerHeader from 'components/ui/Logs/LogsExplorerHeader'
-import { useStore } from 'hooks'
+import { useContentQuery } from 'data/content/content-query'
import { NextPageWithLayout } from 'types'
import { IconSave, Loading } from 'ui'
export const LogsSavedPage: NextPageWithLayout = () => {
- const { content } = useStore()
const { ref } = useParams()
- useEffect(() => {
- content.load()
- }, [ref])
+ const { data, isLoading } = useContentQuery(ref)
- if (content.isLoading) {
+ if (isLoading) {
return <Loading active={true}>{null}</Loading>
}
- const saved = content.savedLogSqlSnippets()
+
+ let saved = [...(data?.content ?? [])].filter((c) => c.type === 'log_sql')
+ saved.sort((a, b) => a.name.localeCompare(b.name))
+
return (
<div className="mx-auto w-full px-5 py-6 h-full">
<LogsExplorerHeader subtitle="Saved Queries" />
diff --git a/studio/stores/RootStore.ts b/studio/stores/RootStore.ts
index 0b8a05e4227..e389209008d 100644
--- a/studio/stores/RootStore.ts
+++ b/studio/stores/RootStore.ts
@@ -2,7 +2,6 @@ import { configure } from 'mobx'
import { Project } from 'types'
import AppStore, { IAppStore } from './app/AppStore'
import MetaStore, { IMetaStore } from './pgmeta/MetaStore'
-import ProjectContentStore, { IProjectContentStore } from './project/ProjectContentStore'
import ProjectFunctionsStore, { IProjectFunctionsStore } from './project/ProjectFunctionsStore'
import VaultStore, { IVaultStore } from './project/VaultStore'
import UiStore, { IUiStore } from './UiStore'
@@ -17,7 +16,6 @@ export interface IRootStore {
app: IAppStore
ui: IUiStore
meta: IMetaStore
- content: IProjectContentStore
functions: IProjectFunctionsStore
vault: IVaultStore
@@ -29,7 +27,6 @@ export class RootStore implements IRootStore {
app: IAppStore
ui: IUiStore
meta: IMetaStore
- content: IProjectContentStore
functions: IProjectFunctionsStore
vault: IVaultStore
@@ -40,7 +37,6 @@ export class RootStore implements IRootStore {
this.ui = new UiStore(this)
this.meta = new MetaStore(this, { projectRef: '', connectionString: '' })
- this.content = new ProjectContentStore(this, { projectRef: '' })
this.functions = new ProjectFunctionsStore(this, { projectRef: '' })
this.vault = new VaultStore(this)
}
@@ -59,7 +55,6 @@ export class RootStore implements IRootStore {
this.meta.setProjectDetails(project)
this.functions.setProjectRef(project.ref)
- this.content.setProjectRef(project.ref)
// ui set must come last
this.ui.setProjectRef(project.ref)
diff --git a/studio/stores/project/ProjectContentStore.ts b/studio/stores/project/ProjectContentStore.ts
deleted file mode 100644
index dda44eaca6f..00000000000
--- a/studio/stores/project/ProjectContentStore.ts
+++ /dev/null
@@ -1,386 +0,0 @@
-import { makeAutoObservable } from 'mobx'
-import { keyBy } from 'lodash'
-
-import { uuidv4 } from 'lib/helpers'
-import { get, post, patch, delete_, isResponseOk } from 'lib/common/fetch'
-import { LogSqlSnippets, UserContent, UserContentMap } from 'types'
-import { IRootStore } from '../RootStore'
-import { API_URL } from 'lib/constants'
-
-// [Joshen] This will be the new ProjectContentStore
-// but use the one under the stores folder projectContentStore first while we transition
-
-type CustomFilter = (content: UserContent) => boolean
-export interface IProjectContentStore {
- isLoading: boolean
- isInitialized: boolean
- isLoaded: boolean
- savingState:
- | 'IDLE'
- | 'CREATING'
- | 'CREATING_FAILED'
- | 'UPDATING_REQUIRED'
- | 'UPDATING'
- | 'UPDATING_FAILED'
- error: any
- recentLogSqlSnippets: LogSqlSnippets.Content[]
-
- baseUrl: string
- projectRef?: string
-
- load: () => Promise<UserContentMap | undefined>
- loadPersistentData: () => Promise<void>
- save: (
- content: UserContent
- ) => Promise<{ data: UserContent; error: null } | { data: null; error: { message: string } }>
- create: (
- content: UserContent
- ) => Promise<{ data: UserContent; error: null } | { data: null; error: { message: string } }>
- createOptimistically: (content: UserContent) => { data: UserContent; error: null }
- list: (filter?: any) => any[]
- reports: (filter?: any) => any[]
- sqlSnippets: (filter?: any) => any[]
- savedLogSqlSnippets: (filter?: CustomFilter) => UserContent[]
- addRecentLogSqlSnippet: (snippet: Partial<LogSqlSnippets.Content>) => void
- clearRecentLogSqlSnippets: () => void
- setProjectRef: (ref?: string) => void
- update: (
- id: any,
- updates: any,
- type: UserContent['type']
- ) => Promise<
- | {
- data: UserContent
- error: null
- }
- | {
- data: null
- error: unknown
- }
- >
- updateSql: (
- id: any,
- updates: any
- ) => Promise<
- | {
- data: UserContent
- error: null
- }
- | {
- data: null
- error: unknown
- }
- >
- updateReport: (
- id: any,
- updates: any
- ) => Promise<
- | {
- data: UserContent
- error: null
- }
- | {
- data: null
- error: unknown
- }
- >
-
- del(id: any): Promise<{ data: boolean; error: unknown }>
- delOptimistically(id: string): { data: boolean; error: null }
- setUpdatingRequired(): void
-}
-
-export default class ProjectContentStore implements IProjectContentStore {
- rootStore: IRootStore
-
- STATES = {
- INITIAL: 'initial',
- LOADING: 'loading',
- ERROR: 'error',
- LOADED: 'loaded',
- }
-
- baseUrl: string
- localStorageKey: string
- recentLogSqlKey: string
- projectRef: string
-
- data: UserContentMap = {}
- recentLogSqlSnippets: LogSqlSnippets.Content[] = []
-
- state = this.STATES.INITIAL
- savingState:
- | 'IDLE'
- | 'CREATING'
- | 'CREATING_FAILED'
- | 'UPDATING_REQUIRED'
- | 'UPDATING'
- | 'UPDATING_FAILED'
- error = null
-
- constructor(rootStore: IRootStore, options: { projectRef: string }) {
- const { projectRef } = options
- this.projectRef = projectRef
- this.rootStore = rootStore
- this.localStorageKey = `project-content-${projectRef}`
- this.recentLogSqlKey = `${this.localStorageKey}-recent-log-sql`
- this.loadPersistentData()
- this.baseUrl = ``
- this.savingState = 'IDLE'
- makeAutoObservable(this)
- }
-
- get isLoading() {
- return this.state === this.STATES.INITIAL || this.state === this.STATES.LOADING
- }
-
- get isInitialized() {
- return this.state !== this.STATES.INITIAL
- }
-
- get isLoaded() {
- return this.state === this.STATES.LOADED
- }
-
- async fetchData() {
- const headers = {
- 'Content-Type': 'application/json',
- }
- const response = await get(this.baseUrl, { headers })
- if (response.error) {
- throw response.error
- }
- this.data = keyBy(response.data, 'id')
- return response
- }
-
- async load() {
- let { LOADING, ERROR, LOADED } = this.STATES
- try {
- this.error = null
- this.state = LOADING
- await this.fetchData()
- this.state = LOADED
- return this.data
- } catch (e: any) {
- console.error('Failed to load project content', e.message)
- this.error = e
- this.state = ERROR
- }
- }
-
- async loadPersistentData() {
- this.loadRecentLogSqlSnippets()
- }
-
- async loadRemotePersistentData(userId: any) {
- const sqlSnippets = this.sqlSnippets((x: any) => x.owner_id === userId)
- }
-
- loadRecentLogSqlSnippets() {
- if (typeof window === 'undefined' || !window.localStorage) return
- this.recentLogSqlSnippets = JSON.parse(
- window.localStorage?.getItem(this.recentLogSqlKey) || '[]'
- )
- }
-
- list(filter?: any) {
- const arr = Object.values(this.data)
- if (!!filter) {
- return arr.filter(filter).sort((a, b) => a.name.localeCompare(b.name))
- } else {
- return arr.sort((a, b) => a.name.localeCompare(b.name))
- }
- }
-
- byId(id: any) {
- return this.data[id]
- }
-
- reports(filter?: any) {
- let arr = Object.values(this.data)
- if (!!filter) {
- return arr
- .filter((x) => x.type == 'report')
- .filter(filter)
- .sort((a, b) => a.name.localeCompare(b.name))
- } else {
- return arr.filter((x) => x.type == 'report').sort((a, b) => a.name.localeCompare(b.name))
- }
- }
-
- sqlSnippets(filter?: any) {
- let arr = Object.values(this.data)
- if (!!filter) {
- const arr_filtered = arr
- .filter((x) => x.type == 'sql')
- .filter(filter)
- .sort((a, b) => a.name.localeCompare(b.name))
-
- return arr_filtered
- } else {
- const arr_filtered = arr
- .filter((x) => x.type == 'sql')
- .sort((a, b) => a.name.localeCompare(b.name))
-
- return arr_filtered
- }
- }
-
- addRecentLogSqlSnippet(snippet: Partial<LogSqlSnippets.Content>) {
- if (typeof window === 'undefined') return
- const defaults: LogSqlSnippets.Content = {
- schema_version: '1',
- favorite: false,
- sql: '',
- content_id: '',
- }
- this.recentLogSqlSnippets.push({ ...defaults, ...snippet })
- ;(window as any).localStorage.setItem(
- this.recentLogSqlKey,
- JSON.stringify(this.recentLogSqlSnippets)
- )
- }
-
- clearRecentLogSqlSnippets() {
- if (typeof window === 'undefined') return
- this.recentLogSqlSnippets = []
- ;(window as any).localStorage.setItem(this.recentLogSqlKey, JSON.stringify([]))
- }
-
- savedLogSqlSnippets(filter?: CustomFilter) {
- let arr = Object.values(this.data) as UserContent[]
- let snippets = arr.filter((c) => c.type === 'log_sql')
- if (filter) {
- snippets = snippets.filter(filter)
- }
- return snippets.sort((a, b) => a.name.localeCompare(b.name))
- }
-
- /**
- * Creates a new content item, but does not update local store
- */
- async save(payload: UserContent) {
- try {
- this.savingState = 'CREATING'
-
- const headers = {
- 'Content-Type': 'application/json',
- }
- const created = await post<UserContent>(this.baseUrl, payload, { headers })
- if (!isResponseOk(created)) {
- throw created.error
- }
-
- this.savingState = 'IDLE'
-
- return { data: created, error: null }
- } catch (error) {
- this.savingState = 'CREATING_FAILED'
-
- return { data: null, error: error as { message: string } }
- }
- }
-
- /**
- * Creates a new content item, and updates local store
- */
- async create(payload: UserContent) {
- const { data, error } = await this.save(payload)
-
- if (error) {
- return { data: null, error }
- }
-
- if (data && data['id']) {
- this.data[data['id']] = data
- }
-
- return { data: data as UserContent, error: null }
- }
-
- /**
- * Creates a new content item locally in store without saving to the server
- */
- createOptimistically(payload: UserContent) {
- const created = { ...payload, id: uuidv4() }
-
- this.data[created.id] = created
-
- return { data: created, error: null }
- }
-
- async update(id: any, updates: any, type?: UserContent['type']) {
- try {
- this.savingState = 'UPDATING'
-
- const headers = {
- 'Content-Type': 'application/json',
- }
- let payload = {
- ...updates,
- id,
- }
- if (type) {
- payload.type = type
- }
-
- const url = `${this.baseUrl}?id=${id}`
- const updated = await patch<UserContent[]>(url, payload, { headers })
- if (!isResponseOk(updated)) {
- throw updated.error
- }
-
- const localUpdate = { ...this.data[id], ...payload }
- this.data[id] = localUpdate
- this.savingState = 'IDLE'
-
- return { data: localUpdate, error: null }
- } catch (error) {
- this.savingState = 'UPDATING_FAILED'
-
- return { data: null, error }
- }
- }
-
- async updateSql(id: any, updates: any) {
- return this.update(id, updates, 'sql')
- }
-
- async updateReport(id: any, updates: any) {
- return this.update(id, updates, 'report')
- }
-
- async del(id: any) {
- try {
- const headers = {
- 'Content-Type': 'application/json',
- }
- const url = `${this.baseUrl}?id=${id}`
- const deleted = await delete_(url, {}, { headers })
- if (deleted.error) throw deleted.error
- delete this.data[id]
- return { data: true, error: null }
- } catch (error) {
- return { data: false, error }
- }
- }
-
- delOptimistically(id: string) {
- delete this.data[id]
- return { data: true, error: null }
- }
-
- setUpdatingRequired() {
- if (this.savingState === 'IDLE' || this.savingState === 'UPDATING_FAILED') {
- this.savingState = 'UPDATING_REQUIRED'
- }
- }
-
- setProjectRef(ref?: string) {
- if (ref) {
- this.projectRef = ref
- this.baseUrl = `${API_URL}/projects/${ref}/content`
- }
- }
-}