sentryFunctionDetails.tsx 6.9 KB

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