Gatsby trailing slash redirect issue only on deployed version - redirect

In my Gatsby app, I want the following routes:
/branches - shows stores' branch locations.
/branches/:id - shows information about a particular branch.
To accomplish this, I have the following folder structure:
src
pages
branches
index.tsx
Inside index.tsx, I have:
import React from 'react'
import { Router } from '#reach/router'
const Comp = (props: { path: any }) => {
return <pre>{JSON.stringify(props, null, 2)}</pre>
}
export default () => {
return (
<Router>
<Comp path="/branches" />
<Comp path="/branches/:id" />
</Router>
)
}
(The Comp component is there just to show the functionality is working.)
In my gatsby-node.js file, I have this:
// Implement the Gatsby API “onCreatePage”. This is
// called after every page is created.
exports.onCreatePage = async ({ page, actions }) => {
const { createPage } = actions
// page.matchPath is a special key that's used for matching pages
// only on the client.
if (page.path.match(/^\/branches/)) {
page.matchPath = '/branches/*'
// Update the page.
createPage(page)
}
}
So the result is that when I am running gatsby develop, everything works as expected. I can visit /branches and /branches/4 and I see what I expect, the Comp component displaying some routing information:
{
"path": "/branches",
"uri": "/branches",
"location": {
"pathname": "/branches/",
"search": "",
"hash": "",
"href": "http://localhost:1337/branches/",
"origin": "http://localhost:1337",
"protocol": "http:",
"host": "localhost:1337",
"hostname": "localhost",
"port": "1337",
"state": null,
"key": "initial"
}
}
However, when running deploying to S3 using gatsby build && gatsby-plugin-s3 deploy --yes, I get into a redirect loop:
What is the issue here and how can I resolve it?
(I have experimented with the gatsby-plugin-force-trailing-slashes and gatsby-plugin-remove-trailing-slashes plugins to no avail)

Related

Strapi email designer plugin reference template to record

I'm currently developing a multi-tenant API with Strapi and for one of the parts I use the Strapi email designer plugin because I want to send some emails but I want them to be custom designed for each tenant, the problem is that the plugin's table is not accessible in the content manager of Strapi so I can only hard code the template to a specific endpoint, is there a way to have the plugin table in the content manager or for it to be referenced to a content manager table something like:
(table)tenant->(field)templateId => (ref-table)plugin-email-designer->(ref-field)templateId
you know so I can switch and set dynamically from the Strapi panel and not with hard-coded endpoints
I've checked your issue briefly, and there is option you are going to like, but it involves using patch-package...
So, let's assume that you have strapi project created and you have added strapi-plugin-email-designer and you are using yarn v1.xx.xx:
yarn add patch-package postinstall-postinstall
Go to node_modules/strapi-plugin-email-designer/server/content-types/email-template/schema.json
change following fileds:
{
...
"pluginOptions": {
"content-manager": {
"visible": true
},
"content-type-builder": {
"visible": true
}
},
...
}
now run
yarn patch-package strapi-plugin-email-designer
now open your projects package.json and add to scripts:
{
"scripts": {
...
"postinstall": "patch-package"
}
}
run
yarn build
yarn develop
head to admin ui, you should see new Collection:
so now you can do that:
Sending Email
Let's assume you added a relation has one called email_template to your model.
Next we need to add custom route, so in /src/api/tenant/routes/ create file called routes.js
/src/api/tenant/routes/routes.js
module.exports = {
routes: [
{
method: 'POST',
path: `/tenants/:id/send`,
handler: `tenant.send`
}
]
}
now, we need to add handler to controller:
/src/api/tenant/controllers/tenant.js
"use strict";
/**
* tenant controller
*/
const { createCoreController } = require("#strapi/strapi").factories;
module.exports = createCoreController("api::tenant.tenant", ({ strapi }) => ({
async send(ctx) {
const { id } = ctx.params;
const { data } = ctx.request.body;
// notice, if you need extra validation you add it here
// if (!data) return ctx.badRequest("no data was provided");
const { to, subject } = data;
const { email_template, ...tenant } = await strapi.db
.query("api::tenant.tenant")
// if you have extra relations it's better to populate them directly here
.findOne({ where: { id }, populate: ["email_template"] });
console.log(email_template);
try {
await strapi
.plugin("email-designer")
.service("email")
.sendTemplatedEmail(
{
to,
//from, < should be set in /config/plugins.js email.settings.defaultFrom
//replayTo < should be set in /config/plugins.js email.settings.defaultReplyTo
},
{
templateReferenceId: email_template.templateReferenceId,
subject,
},
{
...tenant,
// this equals to apply all the data you have in tenant
// this may need to be aligned between your tenant and template
}
);
return { success: `Message sent to ${to}` };
} catch (e) {
strapi.log.debug("📺: ", e);
return ctx.badRequest(null, e);
}
},
}));
don't forget to enable access to /api/tenants/:id/send in admin panel, Settings - Roles
POST http://localhost:1337/api/tenants/1/send
{
"data": {
"to" : "email#example.com",
"subject": "Hello World"
}
}
response:
{
"success": "Message sent to email#example.com"
}
pls note, there is no template validation, e.g. if you give it a wrong template it would not be happy

Cannot test a native Android app using codeceptJS

I have created a codeceptJS project by following the mobile testing setup steps located here: https://codecept.io/mobile/#setting-up
So far, I'm unable to test any apps via simulator; I instead get the following error:
1) login
I should be able to login with the correct username and password:
>> The requested resource could not be found, or a request was received using an HTTP method that is not supported by the mapped resource <<
at Object.getErrorFromResponseBody (node_modules/webdriver/build/utils.js:189:12)
at NodeJSRequest._request (node_modules/webdriver/build/request/index.js:157:31)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
I have verified my appium config using appium-doctor, and there are no issues found.
My codecept.conf.js is as follows:
const path = require('path');
const { setHeadlessWhen } = require('#codeceptjs/configure');
// turn on headless mode when running with HEADLESS=true environment variable
// export HEADLESS=true && npx codeceptjs run
setHeadlessWhen(process.env.HEADLESS);
exports.config = {
tests: './*_test.js',
output: './output',
helpers: {
Appium: {
platform: 'Android',
device: 'emulator',
desiredCapabilities: {
avd: 'Pixel_5_API_28',
app: path.resolve('./sample_apps/Android.apk'),
appActivity: 'com.swaglabsmobileapp.MainActivity'
}
},
},
include: {
I: './steps_file.js'
},
bootstrap: null,
mocha: {},
name: 'appium-codecept-android-POC',
plugins: {
pauseOnFail: {},
retryFailedStep: {
enabled: true
},
tryTo: {
enabled: true
},
screenshotOnFail: {
enabled: true
}
}
}
And here's my package.json as created by codeceptjs init:
{
"name": "appium-codecept-android-POC",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"codeceptjs": "^3.0.7",
"webdriverio": "^7.9.0"
}
}
Finally, my test file is as follows:
Feature('login');
Scenario('I should be able to login with the correct username and password', ({ I }) => {
setTimeout(() => {
I.see('Username');
}, 3000);
I.click('//android.widget.EditText[#content-desc="test-Username"]');
I.fillField('//android.widget.EditText[#content-desc="test-Username"]', 'standard_user');
I.click('//android.widget.EditText[#content-desc="test-Password"]');
I.fillField('//android.widget.EditText[#content-desc="test-Password"]', 'secret_sauce');
I.click('//android.view.ViewGroup[#content-desc="test-LOGIN"]');
I.waitForElement('//android.view.ViewGroup[#content-desc="test-Cart drop zone"]/android.view.ViewGroup/android.widget.TextView', 3)
I.dontSeeElement('//android.view.ViewGroup[#content-desc="test-Error message"]/android.widget.TextView');
});
Scenario('I should not be able to login with an incorrect username or password', ({ I }) => {
setTimeout(() => {
I.see('Username');
}, 3000);
I.click('//android.widget.EditText[#content-desc="test-Username"]');
I.fillField('//android.widget.EditText[#content-desc="test-Username"]', 'bob');
I.click('//android.widget.EditText[#content-desc="test-Password"]');
I.fillField('//android.widget.EditText[#content-desc="test-Password"]', 'secret_sauce');
I.click('//android.view.ViewGroup[#content-desc="test-LOGIN"]');
I.waitForElement('//android.view.ViewGroup[#content-desc="test-Cart drop zone"]/android.view.ViewGroup/android.widget.TextView', 3)
I.dontSeeElement('//android.view.ViewGroup[#content-desc="test-Error message"]/android.widget.TextView');
});
Scenario('I should be able to see details', ({ I }) => {
// login
setTimeout(() => {
I.see('Username');
}, 3000);
I.click('//android.widget.EditText[#content-desc="test-Username"]');
I.fillField('//android.widget.EditText[#content-desc="test-Username"]', 'standard_user');
I.click('//android.widget.EditText[#content-desc="test-Password"]');
I.fillField('//android.widget.EditText[#content-desc="test-Password"]', 'secret_sauce');
I.click('//android.view.ViewGroup[#content-desc="test-LOGIN"]');
I.waitForElement('//android.view.ViewGroup[#content-desc="test-Cart drop zone"]/android.view.ViewGroup/android.widget.TextView', 3)
// should be able to click a label to see details
I.click('(//android.widget.TextView[#content-desc="test-Item title"])[2]');
I.seeElement('//android.view.ViewGroup[#content-desc="test-Description"]/android.widget.TextView[2]');
I.click('//android.view.ViewGroup[#content-desc="test-BACK TO PRODUCTS"]');
});
I'm at a loss here, as I haven't done anything except follow the setup instructions. Executing against ios works; it is only the android execution that fails. Appium is installed and running, env vars are set, etc. Any help would be appreciated, as this could be a deal breaker for me in terms of whether or not I can use codeceptjs. I love the project and really want to use it, but I must be able to test both ios and android native apps.
One final note: If anyone wants to try this config, the app I am using for the above test can be found here: https://github.com/saucelabs/sample-app-mobile/releases/download/2.7.1/Android.SauceLabs.Mobile.Sample.app.2.7.1.apk

How to add a plugin in Aurelia

I am trying to use wavesurfer.js in an Aurelia project. I am not able to use the wavesurfer.js. After building it says Container Element not found.
my app.js looks like this
import * as wavesurfer from '../node_modules/wavesurfer/dist/wavesurfer.js';
export class App {
wavesurferObj = WaveSurfer.create({
container: '#waveform',
waveColor: 'violet',
progressColor: 'purple',
scrollParent: true,
});
constructor() {
wavesurferObj.load('http://ia902606.us.archive.org/35/items/shortpoetry_047_librivox/song_cjrg_teasdale_64kb.mp3');
wavesurferObj.on(ready, function () {
wavesurferObj.play();
});
}
}
and my main.js looks like this
// regenerator-runtime is to support async/await syntax in ESNext.
// If you target latest browsers (have native support), or don't use async/await, you can remove regenerator-runtime.
import * as wavesurfer from '../node_modules/wavesurfer/dist/wavesurfer.js';
// import * as timeline from '../node_modules/wavesurfer/plugin/wavesurfer.timeline.js';
// import * as regions from '../node_modules/wavesurfer/plugin/wavesurfer.regions.js';
import 'regenerator-runtime/runtime';
import * as environment from '../config/environment.json';
import {
PLATFORM
} from 'aurelia-pal';
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.feature(PLATFORM.moduleName('resources/index'));
aurelia.use.plugin(PLATFORM.moduleName('wavesurfer'));
// aurelia.use.plugin(PLATFORM.moduleName('timeline'));
// aurelia.use.plugin(PLATFORM.moduleName('regions'));
aurelia.use.developmentLogging(environment.debug ? 'debug' : 'warn');
if (environment.testing) {
aurelia.use.plugin(PLATFORM.moduleName('aurelia-testing'));
}
aurelia.start().then(() => aurelia.setRoot(PLATFORM.moduleName('app')));
}
and just the build section in Aurelia.json looks like this
"build": {
"options": {
"server": "dev",
"extractCss": "prod",
"coverage": false
},
"bundles": [{
"name": "vendor-bundle.js",
"dependencies": [{
"name": "wavesurfer",
"path": "../node_modules/wavesurfer/dist",
"main": "wavesurfer"
},
{
"name": "wavesurfer.timeline",
"path": "../node_modules/wavesurfer/plugin",
"main": "wavesurfer.timeline",
"deps": [
"wavesurfer"
]
},
{
"name": "wavesurfer.regions",
"path": "../node_modules/wavesurfer/plugin",
"main": "wavesurfer.regions",
"deps": [
"wavesurfer"
]
}
]
}]
},
Here is the error:
WaveSurfer is not defined.
Can someone indicate what is the right way to add this plugin please.
Thanks a lot in advance.
Without having a look at all of your actual code, i'm guessing you have at least 3 errors:
First one is using different variable names: wave surfer is imported as wavesurfer, but the way it's used is WaveSurfer, notice the case.
Using direct path to the dist file in a node_modules package:
import * as wavesurfer from '../node_modules/wavesurfer/dist/wavesurfer.js';
It should be:
import * as wavesurfer from 'wavesurfer';
3rd one is targeting an element via a CSS selector string #waveform. If this is not ready by the time you create an instance of class App, it will not work properly. Where is #waveform? from the document? from app.html? If it's from the document, it's ok, but if it's from app.html, you will need to change that code to something like this
<template>
....
<div ref="waveformElement"></div>
</template>
And in your app code:
import * as WaveSurfer from 'wavesurfer';
export class App {
bind() {
this.wavesurferObj = WaveSurfer.create({
container: this.waveformElement,
waveColor: 'violet',
progressColor: 'purple',
scrollParent: true,
});
this.wavesurferObj.load( 'http://ia902606.us.archive.org/35/items/shortpoetry_047_librivox/song_cjrg_teasdale_64kb.mp3');
this.wavesurferObj.on(ready, () => {
this.wavesurferObj.play();
});
}
}

Protractor W3C capability

I am using Protractor with Selenoid. I need to use the dockerized Windows images so that I can test Internet Explorer and Edge from Linux boxes.
I was able to make it work from curl by running:
curl -X POST http://127.0.0.1:4444/wd/hub/session -d '{"capabilities":{"browserName":"MicrosoftEdge","count":1,"alwaysMatch":{"browserName":"MicrosoftEdge","selenoid:options":{"enableVNC":true,"enableVideo":false,"enableLog":true,"logName":"edge-18.0.log"}}}}'
My protractor config looks like:
multiCapabilities: [
{
browserName: "MicrosoftEdge",
"alwaysMatch": {
browserName: "MicrosoftEdge",
"selenoid:options": {
enableVNC: true,
enableVideo: false,
enableLog: true,
logName: "edge-18.0.log"
}
}
}
]
But protractor send it over the selenoid server like this:
{
"desiredCapabilities": {
"browserName": "MicrosoftEdge",
"count": 1,
"alwaysMatch": {
"browserName": "MicrosoftEdge",
"selenoid:options": {
"enableVNC": true,
"enableVideo": false,
"enableLog": true,
"logName": "edge-18.0.log"
}
}
}
}
The issue is that desiredCapabilities should just be 'capabilities`. I have been looking everywhere trying to find out where is that created so that I can created some sort of flag to be able to switch it.
Any ideas?
Using Protractor 6.0 solve my issue, but broke all my tests.
I was able to keep using 5.4.1 by patching the selenium-webdriver package. Looking at the way Protractor 6 did it, I did it to Protractor 5.4.1:
I edited the file located at node_modules/selenium-webdriver/lib/webdriver.js and added the following:
// Capability names that are defined in the W3C spec.
const W3C_CAPABILITY_NAMES = new Set([
'acceptInsecureCerts',
'browserName',
'browserVersion',
'platformName',
'pageLoadStrategy',
'proxy',
'setWindowRect',
'timeouts',
'unhandledPromptBehavior',
]);
Then in the same file I modify the static createSession(executor, capabilities, opt_flow, opt_onQuit) method to add the following:
let W3CCaps = new Capabilities(capabilities);
for (let k of W3CCaps.keys()) {
// Any key containing a colon is a vendor-prefixed capability.
if (!(W3C_CAPABILITY_NAMES.has(k) || k.indexOf(':') >= 0)) {
W3CCaps.delete(k);
}
}
cmd.setParameter('capabilities', W3CCaps);
After all those changes the request getting to Selenoid is like this:
{
"desiredCapabilities": {
"browserName": "MicrosoftEdge",
"version": "18.0",
"enableVNC": true,
"enableVideo": false,
"count": 1
},
"capabilities": {
"browserName": "MicrosoftEdge"
}
}
And my Protractor 5 config looks like this:
multiCapabilities: [{
browserName: 'MicrosoftEdge',
version: '18.0',
enableVNC: true,
enableVideo: false
}]
Note:
So that I don't have to worry about refresh installs or updates I use the package patch-package (https://github.com/ds300/patch-package) to create a patch that is applied when any of those events happen. Here is a great video explaining how to use that package https://www.youtube.com/watch?v=zBPcVGr6XPk

electron-builder cannot find git repository although specifying

package.json
{
//some other config
"repository": "git#gitintsrv.domain.com/UserName/RepoName",
"scripts": {
"build": "build --win",
"ship": "build --win -p always"
}
}
electron-builder.yml
appId: com.xorchat.app.windows
publish:
provider: github
token: some_token
electron.js
const { app, BrowserWindow, ipcMain } = require('electron');
const { autoUpdater } = require("electron-updater");
let win; // this will store the window object
// creates the default window
function createDefaultWindow() {
win = new BrowserWindow({ width: 900, height: 680 });
win.loadURL(`file://${__dirname}/src/index.html`);
win.on('closed', () => app.quit());
return win;
}
// when the app is loaded create a BrowserWindow and check for updates
app.on('ready', function() {
createDefaultWindow()
autoUpdater.checkForUpdates();
});
// when the update has been downloaded and is ready to be installed, notify the BrowserWindow
autoUpdater.on('update-downloaded', (info) => {
win.webContents.send('updateReady')
});
// when receiving a quitAndInstall signal, quit and install the new version ;)
ipcMain.on("quitAndInstall", (event, arg) => {
autoUpdater.quitAndInstall();
})
When i am running npm run build i am receiving this error.
Error: Cannot detect repository by .git/config. Please specify "repository" in the package.json (https://docs.npmjs.com/files/package.json#repository).
Please see https://electron.build/configuration/publish
Where is the error?
I know it's probably too late, but in case you end up here as I did, here's how I solved it:
Add this to your package.json
"build": {
"publish": [{
"provider": "github",
"host": "github.<<DOMAIN>>.com",
"owner": "<<USER>>",
"repo": "<<NAME OF YOUR REPO (ONLY THE NAME)>>",
"token": "<<ACCESS TOKEN>>"
}]
}
I think the issue is that electron cannot parse corporate github urls, or something.
*********** EDIT:
Make a electron-builder.yml in the root folder, with the following content
appId: com.corporate.AppName
publish:
provider: github
token: <<ACCESS TOKEN>>
host: github.corporate.com
owner: <<User/ Org>>
repo: <<repo name>>
Don't forget to include this file on your .gitignore
This use to be a specific issue with Electron Builder 19x, and it has since been fixed:
https://github.com/electron-userland/electron-builder/issues/2785