How to access privateRuntimeConfig declared in Nuxt.config.js in serverMiddleware? - nuxtjs

How to access configuration declared in privateRuntimeConfig in Nuxt.config.js file in serverMiddleware?
$config and context are not available in serverMiddleware.
I am using serverMiddleware in Nuxtjs to write api.
Its getting called however I am trying to pass some configuration from privateRuntimeConfig in Nuxt.config.js file.
const bodyParser = require('body-parser')
const app = require('express')()
const { uuid } = require('vue-uuid')
const productsModule = require('../lib/bal/products')
app.use(bodyParser.json())
app.post('/create', (req, res) => {
console.log('Config:' + String(req))
const result = productsModule.createProduct(this.$config, req.body.name, 'Trial product', '', 10, false, uuid.v1)
if (result === undefined) {
res.status(500).json({ error: 'Failed to create product. Try again!' })
return
}
console.log(result)
res.status(200).json(result)
})
module.exports = app

Yes you are right, since serverMiddleware only runs at service-side you can't use this.$config or context.$config.
What i did is, if it is a static data, i use environment variables to call the data.
.env file
APP_USERNAME=M457ERCH1EF
serverMiddleware file i.e xxx.js
....
const username = process.env.APP_USERNAME
....

Related

remix fetch data within a loader from another loader

Trying to fetch data internally within remix application
from an api route located in
/routes/api/test.tsx
export const loader = async ({ request }: LoaderArgs) => {
const testRes = await fetch("/api/test");
return await testRes.json();
};
I get error Invalid URL
what is the right convention for this?
If you want to call another URL you have to pass in the full url. Something like:
export const loader = async ({ request }: LoaderArgs) => {
const testRes = await fetch("https://example.com/api/test");
return await testRes.json();
};
To have the domain be dynamically set you could use the URL from the request. Something like this:
export const loader = async ({ request }: LoaderArgs) => {
const domain = new URL(request.url).hostname;
const testRes = await fetch(`${domain}/api/test`);
return await testRes.json();
};

How to use async callback to determine resource to cache in workbox precacheAndRoute

In my service worker, I'm making use of workbox's precacheAndRoute from workbox-precaching. I want to cache files paths that already exist on IndexedDB since it varies across users. My code looks like this:
import { precacheAndRoute } from 'workbox-precaching';
import localforage from "localforage";
let formID;
const cachedFilesStore = localforage.createInstance({
name: 'page-id',
storeName: 'store'
})
const produceValuesFromCache = () => {
return cachedFilesStore.getItem('1')
.then(async (value) => {
formID = formID || value.form_id;
const cachedFiles = await cachedFilesStore.getItem(`${formID}`)
return [
...cachedFiles.manifest,
`/form/${formID}`
]
});
}
precacheAndRoute([], {
urlManipulation: async ({ url }) => {
const files = await produceValuesFromCache();
return files
}
})
It doesn't work as expected, instead I see an error like so: Uncaught TypeError: additionalURLs is not iterable. What am I doing wrong?
The code that dumps the files in IndexedDB is in the index.html file which is located at route form/${formID.

how do I get the section title, sub_section_title and file in the formData in laravel

I am developing an application using laravel 8 and vuejs. I am trying to post form data from my vuejs to backend(laravel) but it is not working
The vuejs creates a subsection of a section which is add to an array of subsection inside the section array which is converted to string and added to a form data then sent as a request to my backend.
The frontend is working perfectly well but I cant access the data on my backend. How do I get the values of the course title, section title, sub section title and file added
Vuejs
<script>
import { reactive } from "vue";
import axios from "axios";
export default {
name: 'CreateCourse',
setup(){
const sections = reactive([{'section_title': '', 'sub_sections': [{'sub_section_title': '', 'file': '', 'url': ''}]}]);
const course = reactive({'title': '', 'description': ''});
const addSection = () => {
sections.push({"section_title": "", 'sub_sections': [{'sub_section_title': '', 'file': '', 'url': ''}]});
}
const addSubSection = (idx) => {
console.log('the value of idx is ', idx);
sections[idx].sub_sections.push({"sub_section_title": "", 'file': '', 'url': ''});
}
const uploadFile = (e, idx, i) => {
sections[idx].sub_sections[i].file = e.target.files[0];
sections[idx].sub_sections[i].url = URL.createObjectURL(sections[idx].sub_sections[i].file);
}
const createCourse = (e) => {
e.preventDefault();
let newCourse = JSON.stringify(course)
let newSection = JSON.stringify(sections)
const formData = new FormData();
formData.append("course", newCourse);
formData.append("sections", newSection);
showLoader(true);
axios.post('/api', form, { headers: {'Content-Type': 'multipart/form-data'}}).then(response =>
{
NotificationService.success(response.data.message);
showLoader(false);
course.title = '';
course.description = '';
}).catch(err => {
NotificationService.error(err.response);
showLoader(false);
});
}
return {
course,
createCourse,
sections,
addSection,
addSubSection,
uploadFile
}
}
</script>
laravel code
echo $request->get("title");
echo $request->get("description");
foreach($request->section_title as $titles)
{
echo $titles
}
foreach($request->section_sub_title as $sub_titles)
{
// info($sub_titles);
// return $sub_titles;
echo $sub_titles
}
{"course":{"title":"Frontend","description":"This is building web interface with html, css and javascript"},"sections":[{"section_title":"HTML","sub_sections":[{"sub_section_title":"What is HTML","file":{},"url":"blob:http://localhost:8080/ea0acc7d-34e6-4bff-9255-67794acd8fab"}]}]}
Bit tricky to understand where you're stuck, but let's give it a shot:
Does the api request actually reach your route (post -> /api), do you see in the network tab a post request to the route?
Have you tried running dd($request->all()) in the controller method so see what you're getting (just do this on the first line inside your method)?
Small gotcha moment:
Sometimes it helps to run the php artisan route:clearcommand

Parallel requests in cypress

I want to make parallel requests in cypress. I define a command for that:
const resetDb = () => {
const apiUrl = `${Cypress.config().baseUrl}/api`;
Cypress.Promise.all([
cy.request(`${apiUrl}/group/seed/resetDb`),
cy.request(`${apiUrl}/auth/seed/resetDb`),
cy.request(`${apiUrl}/email/seed/resetDb`),
]);
};
Cypress.Commands.add('resetDb', resetDb);
However, it is still making those requests in sequence. What am I doing wrong?
I was able to solve this problem using task in Cypress, which allows you to use nodejs API.
In the plugins index file, I define a task as follows:
const fetch = require('isomorphic-unfetch');
module.exports = on => {
on('task', {
resetDb() {
const apiUrl = `http://my.com/api`;
return Promise.all([
fetch(`${apiUrl}/group/seed/resetDb`),
fetch(`${apiUrl}/auth/seed/resetDb`),
fetch(`${apiUrl}/email/seed/resetDb`),
]);
},
});
};
The it can be used as follows:
before(() => {
return cy.task('resetDb');
});

How do you dynamically load launch_url and append a relative path to it

I am trying to use the property launch_url in my tests and append a relative path to it before sending the browser to that url.
I know that browser.init(); send the browser to the address in launch_url but I was wondering if it is possible to append some string to the retrieved url before executing the redirect.
Assuming my launch_url is www.xxx.com, I'd like to do something like:
this.test = function (client) {
client.init("/a/b/c"); // >> should result in the browser going to www.xxx.com/a/b/c
};
Any idea?
Thanks
If you have specified a "launch_url" in your nightwatch.json file, you can access it on the 'client' object passed into your tests. For example:
module.exports = {
'Demo test Google' : function (client) {
client
.url(client.launch_url)
.waitForElementVisible('body', 1000)
.setValue('input[type=text]', 'nightwatch')
.waitForElementVisible('button[name=btnG]', 1000)
.click('button[name=btnG]')
.pause(1000)
.assert.containsText('#main', 'Night Watch')
.end();
}
};
So, for your example code:
this.test = function (client) {
client.url(client.launch_url + "/a/b/c"); // >> should result in the browser going to www.xxx.com/a/b/c
};
An alternative would be to create a config file with some base items in it; then be able to append that config file through a custom init method you use.
IE:
var configDefaults = module.exports = {
baseUrl: 'http://www.example.com/',
local: false,
};
Then in your custom command write something like:
"use strict";
var config = require('./config')
exports.command = function(urlModifier) {
var _self = this;
_self
.url(config.baseUrl+urlModifier)
.waitForElementVisible('body', 4000)
if( typeof callback === "function"){
callback.call(_self);
}
return this;
};

Resources