techtools

api.js

JavaScript · 80 рядків

1async function call(url, options) {
2  const response = await fetch(url, {
3    headers: { 'content-type': 'application/json' },
4    ...options
5  })
6  if (response.status === 204) return null
7
8  const text = await response.text()
9  let body
10  try {
11    body = JSON.parse(text)
12  } catch {
13    throw new Error(
14      `API returned a non-JSON response (${response.status}). `
15      + 'Restart the Node.js backend and try again.'
16    )
17  }
18
19  if (!response.ok) {
20    const error = new Error(body.error || 'Request failed')
21    error.details = body
22    throw error
23  }
24  return body
25}
26
27export const api = {
28  workflows: () => call('/api/workflows'),
29  workflow: id => call(`/api/workflows/${id}`),
30  createWorkflow: workflow => call('/api/workflows', {
31    method: 'POST',
32    body: JSON.stringify(workflow)
33  }),
34  save: workflow => call(`/api/workflows/${workflow.id}`, {
35    method: 'PUT',
36    body: JSON.stringify(workflow)
37  }),
38  publish: id => call(`/api/workflows/${id}/publish`, { method: 'POST' }),
39  discardDraft: id => call(`/api/workflows/${id}/draft`, { method: 'DELETE' }),
40  versions: id => call(`/api/workflows/${id}/versions`),
41  notifications: workflowId => call(`/api/notifications?workflowId=${workflowId}`),
42  validateWorkflow: workflow => call('/api/workflows/validate', {
43    method: 'POST',
44    body: JSON.stringify(workflow)
45  }),
46  deleteWorkflow: id => call(`/api/workflows/${id}`, {
47    method: 'DELETE'
48  }),
49  execute: (id, event) => call(`/api/workflows/${id}/execute`, {
50    method: 'POST',
51    body: JSON.stringify(event)
52  }),
53  event: event => call('/api/events?responseMode=sync', {
54    method: 'POST',
55    body: JSON.stringify(event)
56  }),
57  executions: workflowId => call(`/api/executions?workflowId=${workflowId}`),
58  execution: id => call(`/api/executions/${id}`),
59  dashboard: () => call('/api/dashboard'),
60  tasks: (filters = {}) => {
61    const query = new URLSearchParams(
62      Object.entries(filters)
63        .filter(([, value]) => value !== '' && value !== undefined && value !== null)
64    )
65    return call(`/api/tasks?${query}`)
66  },
67  models: () => call('/api/models'),
68  createModel: model => call('/api/models', {
69    method: 'POST',
70    body: JSON.stringify(model)
71  }),
72  updateModel: model => call(`/api/models/${model.id}`, {
73    method: 'PUT',
74    body: JSON.stringify(model)
75  }),
76  deleteModel: id => call(`/api/models/${id}`, {
77    method: 'DELETE'
78  })
79}
80