sentryFunctionDetails.tsx 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  1. import {useEffect, useState} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import Editor from '@monaco-editor/react';
  4. import {
  5. addErrorMessage,
  6. addLoadingMessage,
  7. addSuccessMessage,
  8. } from 'sentry/actionCreators/indicator';
  9. import Feature from 'sentry/components/acl/feature';
  10. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  11. import Form from 'sentry/components/forms/form';
  12. import JsonForm from 'sentry/components/forms/jsonForm';
  13. import FormModel from 'sentry/components/forms/model';
  14. import {Field} from 'sentry/components/forms/types';
  15. import Panel from 'sentry/components/panels/panel';
  16. import PanelBody from 'sentry/components/panels/panelBody';
  17. import PanelHeader from 'sentry/components/panels/panelHeader';
  18. import {t} from 'sentry/locale';
  19. import {Organization, SentryFunction} from 'sentry/types';
  20. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  21. import withOrganization from 'sentry/utils/withOrganization';
  22. import SentryFunctionEnvironmentVariables from './sentryFunctionsEnvironmentVariables';
  23. import SentryFunctionSubscriptions from './sentryFunctionSubscriptions';
  24. function transformData(data: Record<string, any>) {
  25. const events: string[] = [];
  26. if (data.onIssue) {
  27. events.push('issue');
  28. }
  29. if (data.onError) {
  30. events.push('error');
  31. }
  32. if (data.onComment) {
  33. events.push('comment');
  34. }
  35. delete data.onIssue;
  36. delete data.onError;
  37. delete data.onComment;
  38. data.events = events;
  39. const envVariables: EnvVariable[] = [];
  40. let i = 0;
  41. while (data[`env-variable-name-${i}`]) {
  42. if (data[`env-variable-value-${i}`]) {
  43. envVariables.push({
  44. name: data[`env-variable-name-${i}`],
  45. value: data[`env-variable-value-${i}`],
  46. });
  47. }
  48. delete data[`env-variable-name-${i}`];
  49. delete data[`env-variable-value-${i}`];
  50. i++;
  51. }
  52. data.envVariables = envVariables;
  53. const {...output} = data;
  54. return output;
  55. }
  56. type Props = {
  57. sentryFunction?: SentryFunction;
  58. } & WrapperProps;
  59. type EnvVariable = {
  60. name: string;
  61. value: string;
  62. };
  63. const formFields: Field[] = [
  64. {
  65. name: 'name',
  66. type: 'string',
  67. required: true,
  68. placeholder: 'e.g. My Sentry Function',
  69. label: 'Name',
  70. help: 'Human readable name of your Sentry Function',
  71. },
  72. {
  73. name: 'author',
  74. type: 'string',
  75. placeholder: 'e.g. Acme Software',
  76. label: 'Author',
  77. help: 'The company or person who built and maintains this Sentry Function.',
  78. },
  79. {
  80. name: 'overview',
  81. type: 'string',
  82. placeholder: 'e.g. This Sentry Function does something useful',
  83. label: 'Overview',
  84. help: 'A short description of your Sentry Function.',
  85. },
  86. ];
  87. function SentryFunctionDetails(props: Props) {
  88. const [form] = useState(() => new FormModel({transformData}));
  89. const {functionSlug} = props.params;
  90. const {organization, sentryFunction} = props;
  91. const method = functionSlug ? 'PUT' : 'POST';
  92. let endpoint = `/organizations/${organization.slug}/functions/`;
  93. if (functionSlug) {
  94. endpoint += `${functionSlug}/`;
  95. }
  96. const defaultCode = sentryFunction
  97. ? sentryFunction.code
  98. : `exports.yourFunction = (req, res) => {
  99. let message = req.query.message || req.body.message || 'Hello World!';
  100. console.log('Query: ' + req.query);
  101. console.log('Body: ' + req.body);
  102. res.status(200).send(message);
  103. };`;
  104. const [events, setEvents] = useState(sentryFunction?.events || []);
  105. useEffect(() => {
  106. form.setValue('onIssue', events.includes('issue'));
  107. form.setValue('onError', events.includes('error'));
  108. form.setValue('onComment', events.includes('comment'));
  109. }, [form, events]);
  110. const [envVariables, setEnvVariables] = useState(
  111. sentryFunction?.env_variables?.length
  112. ? sentryFunction?.env_variables
  113. : [{name: '', value: ''}]
  114. );
  115. const handleSubmitError = err => {
  116. let errorMessage = t('Unknown Error');
  117. if (err.status >= 400 && err.status < 500) {
  118. errorMessage = err?.responseJSON.detail ?? errorMessage;
  119. }
  120. addErrorMessage(errorMessage);
  121. };
  122. const handleSubmitSuccess = data => {
  123. addSuccessMessage(t('Sentry Function successfully saved.', data.name));
  124. const baseUrl = `/settings/${organization.slug}/developer-settings/sentry-functions/`;
  125. const url = `${baseUrl}${data.slug}/`;
  126. if (sentryFunction) {
  127. addSuccessMessage(t('%s successfully saved.', data.name));
  128. } else {
  129. addSuccessMessage(t('%s successfully created.', data.name));
  130. }
  131. browserHistory.push(normalizeUrl(url));
  132. };
  133. function handleEditorChange(value, _event) {
  134. form.setValue('code', value);
  135. }
  136. return (
  137. <div>
  138. <Feature features={['organizations:sentry-functions']}>
  139. <h2>
  140. {sentryFunction ? t('Editing Sentry Function') : t('Create Sentry Function')}
  141. </h2>
  142. <Form
  143. apiMethod={method}
  144. apiEndpoint={endpoint}
  145. model={form}
  146. onPreSubmit={() => {
  147. addLoadingMessage(t('Saving changes..'));
  148. }}
  149. initialData={{
  150. code: defaultCode,
  151. events,
  152. envVariables,
  153. ...props.sentryFunction,
  154. }}
  155. onSubmitError={handleSubmitError}
  156. onSubmitSuccess={handleSubmitSuccess}
  157. >
  158. <JsonForm forms={[{title: t('Sentry Function Details'), fields: formFields}]} />
  159. <Panel>
  160. <PanelHeader>{t('Webhooks')}</PanelHeader>
  161. <PanelBody>
  162. <SentryFunctionSubscriptions events={events} setEvents={setEvents} />
  163. </PanelBody>
  164. </Panel>
  165. <Panel>
  166. <SentryFunctionEnvironmentVariables
  167. envVariables={envVariables}
  168. setEnvVariables={setEnvVariables}
  169. />
  170. </Panel>
  171. <Panel>
  172. <PanelHeader>{t('Write your Code Below')}</PanelHeader>
  173. <PanelBody>
  174. <Editor
  175. height="40vh"
  176. theme="light"
  177. defaultLanguage="javascript"
  178. defaultValue={defaultCode}
  179. onChange={handleEditorChange}
  180. options={{
  181. minimap: {
  182. enabled: false,
  183. },
  184. scrollBeyondLastLine: false,
  185. }}
  186. />
  187. </PanelBody>
  188. </Panel>
  189. </Form>
  190. </Feature>
  191. </div>
  192. );
  193. }
  194. type WrapperState = {
  195. sentryFunction?: SentryFunction;
  196. } & DeprecatedAsyncComponent['state'];
  197. type WrapperProps = {
  198. organization: Organization;
  199. params: {functionSlug?: string};
  200. } & DeprecatedAsyncComponent['props'];
  201. class SentryFunctionsWrapper extends DeprecatedAsyncComponent<
  202. WrapperProps,
  203. WrapperState
  204. > {
  205. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  206. const {functionSlug} = this.props.params;
  207. const {organization} = this.props;
  208. if (functionSlug) {
  209. return [
  210. [
  211. 'sentryFunction',
  212. `/organizations/${organization.slug}/functions/${functionSlug}/`,
  213. ],
  214. ];
  215. }
  216. return [];
  217. }
  218. renderBody() {
  219. return (
  220. <SentryFunctionDetails sentryFunction={this.state.sentryFunction} {...this.props} />
  221. );
  222. }
  223. }
  224. export default withOrganization(SentryFunctionsWrapper);