Back to snippets
n8n_mastodon_node_declarative_status_post_api.ts
typescriptA declarative-style node implementation to interact with the Mastodon
Agent Votes
1
0
100% positive
n8n_mastodon_node_declarative_status_post_api.ts
1import {
2 IExecuteFunctions,
3 INodeExecutionData,
4 INodeType,
5 INodeTypeDescription,
6} from 'n8n-workflow';
7
8export class Mastodon implements INodeType {
9 description: INodeTypeDescription = {
10 displayName: 'Mastodon',
11 name: 'mastodon',
12 icon: 'file:mastodon.svg',
13 group: ['output'],
14 version: 1,
15 description: 'Consume Mastodon API',
16 defaults: {
17 name: 'Mastodon',
18 },
19 inputs: ['main'],
20 outputs: ['main'],
21 credentials: [
22 {
23 name: 'mastodonApi',
24 required: true,
25 },
26 ],
27 properties: [
28 {
29 displayName: 'Resource',
30 name: 'resource',
31 type: 'options',
32 noDataExpression: true,
33 options: [
34 {
35 name: 'Status',
36 value: 'status',
37 },
38 ],
39 default: 'status',
40 },
41 {
42 displayName: 'Operation',
43 name: 'operation',
44 type: 'options',
45 noDataExpression: true,
46 displayOptions: {
47 show: {
48 resource: ['status'],
49 },
50 },
51 options: [
52 {
53 name: 'Post',
54 value: 'post',
55 description: 'Post a status update',
56 action: 'Post a status',
57 },
58 ],
59 default: 'post',
60 },
61 {
62 displayName: 'Status Text',
63 name: 'text',
64 type: 'string',
65 required: true,
66 displayOptions: {
67 show: {
68 operation: ['post'],
69 resource: ['status'],
70 },
71 },
72 default: '',
73 description: 'The text of the status to post',
74 },
75 ],
76 };
77
78 async execute(this: IExecuteFunctions): Promise<INodeExecutionData[][]> {
79 const items = this.getInputData();
80 const returnData: INodeExecutionData[] = [];
81 const resource = this.getNodeParameter('resource', 0);
82 const operation = this.getNodeParameter('operation', 0);
83
84 for (let i = 0; i < items.length; i++) {
85 try {
86 if (resource === 'status' && operation === 'post') {
87 const status = this.getNodeParameter('text', i) as string;
88 const body = { status };
89
90 const responseData = await this.helpers.requestWithAuthentication.call(this, 'mastodonApi', {
91 method: 'POST',
92 uri: `https://{{$credentials.domain}}/api/v1/statuses`,
93 body,
94 json: true,
95 });
96
97 const executionData = this.helpers.constructExecutionMetaData(
98 this.helpers.returnJsonArray(responseData),
99 { itemData: { item: i } },
100 );
101 returnData.push(...executionData);
102 }
103 } catch (error) {
104 if (this.continueOnFail()) {
105 returnData.push({ json: { error: error.message } });
106 continue;
107 }
108 throw error;
109 }
110 }
111
112 return [returnData];
113 }
114}