Compare commits

..

2 Commits

Author SHA1 Message Date
Ali BARIN
6bafdf5257 refactor(http-client): inherit interceptors from parent instance 2024-07-25 07:52:27 +00:00
Ali BARIN
ade6282013 feat(formatter/text): add regex support in replace transfomer 2024-07-25 07:52:21 +00:00
10 changed files with 121 additions and 216 deletions

View File

@@ -89,8 +89,6 @@ export default defineAction({
const response = await $.http.post('/', payload); const response = await $.http.post('/', payload);
console.log(response.config.additionalProperties.extraData);
$.setActionItem({ $.setActionItem({
raw: response.data, raw: response.data,
}); });

View File

@@ -1,7 +1,4 @@
const addAuthHeader = ($, requestConfig) => { const addAuthHeader = ($, requestConfig) => {
console.log('requestConfig', requestConfig)
if (requestConfig.additionalProperties?.skip) return requestConfig;
if ($.auth.data.serverUrl) { if ($.auth.data.serverUrl) {
requestConfig.baseURL = $.auth.data.serverUrl; requestConfig.baseURL = $.auth.data.serverUrl;
} }

View File

@@ -1,23 +0,0 @@
const asyncBeforeRequest = async ($, requestConfig) => {
if (requestConfig.additionalProperties?.skip)
return requestConfig;
const response = await $.http.post(
'http://localhost:3000/webhooks/flows/8a040f4e-817f-4076-80ba-3c1c0af7e65e/sync',
null,
{
additionalProperties: {
skip: true,
},
}
);
console.log(response);
requestConfig.additionalProperties = {
extraData: response.data
}
return requestConfig;
};
export default asyncBeforeRequest;

View File

@@ -1,6 +1,5 @@
import defineApp from '../../helpers/define-app.js'; import defineApp from '../../helpers/define-app.js';
import addAuthHeader from './common/add-auth-header.js'; import addAuthHeader from './common/add-auth-header.js';
import asyncBeforeRequest from './common/async-before-request.js';
import auth from './auth/index.js'; import auth from './auth/index.js';
import actions from './actions/index.js'; import actions from './actions/index.js';
@@ -13,7 +12,7 @@ export default defineApp({
baseUrl: 'https://ntfy.sh', baseUrl: 'https://ntfy.sh',
apiBaseUrl: 'https://ntfy.sh', apiBaseUrl: 'https://ntfy.sh',
primaryColor: '56bda8', primaryColor: '56bda8',
beforeRequest: [asyncBeforeRequest, addAuthHeader], beforeRequest: [addAuthHeader],
auth, auth,
actions, actions,
}); });

View File

@@ -3,100 +3,70 @@ import { HttpsProxyAgent } from 'https-proxy-agent';
import { HttpProxyAgent } from 'http-proxy-agent'; import { HttpProxyAgent } from 'http-proxy-agent';
import appConfig from '../config/app.js'; import appConfig from '../config/app.js';
export function createInstance(customConfig = {}, { requestInterceptor, responseErrorInterceptor } = {}) { const config = axios.defaults;
const config = { const httpProxyUrl = appConfig.httpProxy;
...axios.defaults, const httpsProxyUrl = appConfig.httpsProxy;
...customConfig const supportsProxy = httpProxyUrl || httpsProxyUrl;
}; const noProxyEnv = appConfig.noProxy;
const httpProxyUrl = appConfig.httpProxy; const noProxyHosts = noProxyEnv ? noProxyEnv.split(',').map(host => host.trim()) : [];
const httpsProxyUrl = appConfig.httpsProxy;
const supportsProxy = httpProxyUrl || httpsProxyUrl;
const noProxyEnv = appConfig.noProxy;
const noProxyHosts = noProxyEnv ? noProxyEnv.split(',').map(host => host.trim()) : [];
if (supportsProxy) { if (supportsProxy) {
if (httpProxyUrl) { if (httpProxyUrl) {
config.httpAgent = new HttpProxyAgent(httpProxyUrl); config.httpAgent = new HttpProxyAgent(httpProxyUrl);
}
if (httpsProxyUrl) {
config.httpsAgent = new HttpsProxyAgent(httpsProxyUrl);
}
config.proxy = false;
} }
const instance = axios.create(config); if (httpsProxyUrl) {
config.httpsAgent = new HttpsProxyAgent(httpsProxyUrl);
function shouldSkipProxy(hostname) {
return noProxyHosts.some(noProxyHost => {
return hostname.endsWith(noProxyHost) || hostname === noProxyHost;
});
};
/**
* The interceptors are executed in the reverse order they are added.
*/
instance.interceptors.request.use(
function skipProxyIfInNoProxy(requestConfig) {
const hostname = new URL(requestConfig.baseURL).hostname;
if (supportsProxy && shouldSkipProxy(hostname)) {
requestConfig.httpAgent = undefined;
requestConfig.httpsAgent = undefined;
}
return requestConfig;
},
(error) => Promise.reject(error)
);
// not always we have custom request interceptors
if (requestInterceptor) {
instance.interceptors.request.use(
async function customInterceptor(requestConfig) {
let newRequestConfig = requestConfig;
for (const interceptor of requestInterceptor) {
newRequestConfig = await interceptor(newRequestConfig);
}
return newRequestConfig;
}
);
} }
instance.interceptors.request.use( config.proxy = false;
function removeBaseUrlForAbsoluteUrls(requestConfig) {
/**
* If the URL is an absolute URL, we remove its origin out of the URL
* and set it as baseURL. This lets us streamlines the requests made by Automatisch
* and requests made by app integrations.
*/
try {
const url = new URL(requestConfig.url);
requestConfig.baseURL = url.origin;
requestConfig.url = url.pathname + url.search;
return requestConfig;
} catch (err) {
return requestConfig;
}
},
(error) => Promise.reject(error)
);
// not always we have custom response error interceptor
if (responseErrorInterceptor) {
instance.interceptors.response.use(
(response) => response,
responseErrorInterceptor
);
}
return instance;
} }
const defaultInstance = createInstance(); const axiosWithProxyInstance = axios.create(config);
export default defaultInstance; function shouldSkipProxy(hostname) {
return noProxyHosts.some(noProxyHost => {
return hostname.endsWith(noProxyHost) || hostname === noProxyHost;
});
};
/**
* The interceptors are executed in the reverse order they are added.
*/
axiosWithProxyInstance.interceptors.request.use(
function skipProxyIfInNoProxy(requestConfig) {
const hostname = new URL(requestConfig.baseURL).hostname;
if (supportsProxy && shouldSkipProxy(hostname)) {
requestConfig.httpAgent = undefined;
requestConfig.httpsAgent = undefined;
}
return requestConfig;
},
undefined,
{ synchronous: true }
);
axiosWithProxyInstance.interceptors.request.use(
function removeBaseUrlForAbsoluteUrls(requestConfig) {
/**
* If the URL is an absolute URL, we remove its origin out of the URL
* and set it as baseURL. This lets us streamlines the requests made by Automatisch
* and requests made by app integrations.
*/
try {
const url = new URL(requestConfig.url);
requestConfig.baseURL = url.origin;
requestConfig.url = url.pathname + url.search;
return requestConfig;
} catch {
return requestConfig;
}
},
undefined,
{ synchronous: true}
);
export default axiosWithProxyInstance;

View File

@@ -1,6 +1,6 @@
import { beforeEach, describe, it, expect, vi } from 'vitest'; import { beforeEach, describe, it, expect, vi } from 'vitest';
describe('Custom default axios with proxy', () => { describe('Axios with proxy', () => {
beforeEach(() => { beforeEach(() => {
vi.resetModules(); vi.resetModules();
}); });
@@ -23,13 +23,7 @@ describe('Custom default axios with proxy', () => {
expect(secondRequestInterceptor.fulfilled.name).toBe('removeBaseUrlForAbsoluteUrls'); expect(secondRequestInterceptor.fulfilled.name).toBe('removeBaseUrlForAbsoluteUrls');
}); });
it('should throw with invalid url (consisting of path alone)', async () => { describe('skipProxyIfInNoProxy', () => {
const axios = (await import('./axios-with-proxy.js')).default;
await expect(() => axios('/just-a-path')).rejects.toThrowError('Invalid URL');
});
describe('with skipProxyIfInNoProxy interceptor', () => {
let appConfig, axios; let appConfig, axios;
beforeEach(async() => { beforeEach(async() => {
appConfig = (await import('../config/app.js')).default; appConfig = (await import('../config/app.js')).default;
@@ -73,7 +67,7 @@ describe('Custom default axios with proxy', () => {
}); });
}); });
describe('with removeBaseUrlForAbsoluteUrls interceptor', () => { describe('removeBaseUrlForAbsoluteUrls', () => {
let axios; let axios;
beforeEach(async() => { beforeEach(async() => {
axios = (await import('./axios-with-proxy.js')).default; axios = (await import('./axios-with-proxy.js')).default;
@@ -122,48 +116,4 @@ describe('Custom default axios with proxy', () => {
expect(interceptedRequestConfig.url).toBe('/path?query=1'); expect(interceptedRequestConfig.url).toBe('/path?query=1');
}); });
}); });
describe('with extra requestInterceptors', () => {
it('should apply extra request interceptors in the middle', async () => {
const { createInstance } = await import('./axios-with-proxy.js');
const interceptor = (config) => {
config.test = true;
return config;
}
const instance = createInstance({}, {
requestInterceptor: [
interceptor
]
});
const requestInterceptors = instance.interceptors.request.handlers;
const customInterceptor = requestInterceptors[1].fulfilled;
expect(requestInterceptors.length).toBe(3);
await expect(customInterceptor({})).resolves.toStrictEqual({ test: true });
});
it('should work with a custom interceptor setting a baseURL and a request to path', async () => {
const { createInstance } = await import('./axios-with-proxy.js');
const interceptor = (config) => {
config.baseURL = 'http://localhost';
return config;
}
const instance = createInstance({}, {
requestInterceptor: [
interceptor
]
});
try {
await instance.get('/just-a-path');
} catch (error) {
expect(error.config.baseURL).toBe('http://localhost');
expect(error.config.url).toBe('/just-a-path');
}
})
});
}); });

View File

@@ -1,43 +1,65 @@
import HttpError from '../../errors/http.js'; import HttpError from '../../errors/http.js';
import { createInstance } from '../axios-with-proxy.js'; import axios from '../axios-with-proxy.js';
// Mutates the `toInstance` by copying the request interceptors from `fromInstance`
const copyRequestInterceptors = (fromInstance, toInstance) => {
// Copy request interceptors
fromInstance.interceptors.request.forEach(interceptor => {
toInstance.interceptors.request.use(
interceptor.fulfilled,
interceptor.rejected,
{
synchronous: interceptor.synchronous,
runWhen: interceptor.runWhen
}
);
});
}
export default function createHttpClient({ $, baseURL, beforeRequest = [] }) { export default function createHttpClient({ $, baseURL, beforeRequest = [] }) {
async function interceptResponseError(error) { const instance = axios.create({
const { config, response } = error; baseURL,
// Do not destructure `status` from `error.response` because it might not exist });
const status = response?.status;
if ( // 1. apply the beforeRequest functions from the app
// TODO: provide a `shouldRefreshToken` function in the app instance.interceptors.request.use((requestConfig) => {
(status === 401 || status === 403) && const result = beforeRequest.reduce((newConfig, beforeRequestFunc) => {
$.app.auth && return beforeRequestFunc($, newConfig);
$.app.auth.refreshToken && }, requestConfig);
!$.app.auth.isRefreshTokenRequested
) {
$.app.auth.isRefreshTokenRequested = true;
await $.app.auth.refreshToken($);
// retry the previous request before the expired token error return result;
const newResponse = await instance.request(config); });
$.app.auth.isRefreshTokenRequested = false;
return newResponse; // 2. inherit the request inceptors from the parent instance
copyRequestInterceptors(axios, instance);
instance.interceptors.response.use(
(response) => response,
async (error) => {
const { config, response } = error;
// Do not destructure `status` from `error.response` because it might not exist
const status = response?.status;
if (
// TODO: provide a `shouldRefreshToken` function in the app
(status === 401 || status === 403) &&
$.app.auth &&
$.app.auth.refreshToken &&
!$.app.auth.isRefreshTokenRequested
) {
$.app.auth.isRefreshTokenRequested = true;
await $.app.auth.refreshToken($);
// retry the previous request before the expired token error
const newResponse = await instance.request(config);
$.app.auth.isRefreshTokenRequested = false;
return newResponse;
}
throw new HttpError(error);
} }
);
throw new HttpError(error);
};
const instance = createInstance(
{
baseURL,
},
{
requestInterceptor: beforeRequest.map((originalBeforeRequest) => {
return async (requestConfig) => await originalBeforeRequest($, requestConfig);
}),
responseErrorInterceptor: interceptResponseError,
}
)
return instance; return instance;
} }

View File

@@ -63,8 +63,6 @@ export default async (flowId, request, response) => {
}); });
if (testRun) { if (testRun) {
response.status(204).end();
// in case of testing, we do not process the whole process. // in case of testing, we do not process the whole process.
continue; continue;
} }
@@ -76,12 +74,6 @@ export default async (flowId, request, response) => {
executionId, executionId,
}); });
if (actionStep.appKey === 'filter' && !actionExecutionStep.dataOut) {
response.status(422).end();
break;
}
if (actionStep.key === 'respondWith' && !response.headersSent) { if (actionStep.key === 'respondWith' && !response.headersSent) {
const { headers, statusCode, body } = actionExecutionStep.dataOut; const { headers, statusCode, body } = actionExecutionStep.dataOut;

View File

@@ -14,7 +14,7 @@ connection in Automatisch. If any of the steps are outdated, please let us know!
7. Click on the **Select all** and then click on the **Create** button. 7. Click on the **Select all** and then click on the **Create** button.
8. Now, copy your **API key secret** and paste the key into the **API Key** field in Automatisch. 8. Now, copy your **API key secret** and paste the key into the **API Key** field in Automatisch.
9. Write any screen name to be displayed in Automatisch. 9. Write any screen name to be displayed in Automatisch.
10. You can find your project ID next to your project name. Paste the id into **Project ID** field in Automatisch. 10. You can find your project ID next to your project name. Paste the id into **Project ID** field in Automatsich.
11. If you are using self-hosted Appwrite project, you can paste the instance url into **Appwrite instance URL** field in Automatisch. 11. If you are using self-hosted Appwrite project, you can paste the instace url into **Appwrite instance URL** field in Automatisch.
12. Fill the host name field with the hostname of your instance URL. It's either `cloud.appwrite.io` or hostname of your instance URL. 12. Fill the host name field with the hostname of your instance URL. It's either `cloud.appwrite.io` or hostname of your instance URL.
13. Start using Appwrite integration with Automatisch! 13. Start using Appwrite integration with Automatisch!

View File

@@ -1,7 +1,7 @@
--- ---
favicon: /favicons/appwrite.svg favicon: /favicons/appwrite.svg
items: items:
- name: New documents - name: New documets
desc: Triggers when a new document is created. desc: Triggers when a new document is created.
--- ---