create new vue instance in Vue 3 use require js - requirejs

I have vue instance which is vue 2. The code is below. It seems add axios to prototype then return new vue.
(function () {
define('newVueInstance', ['axios'], (axios) => {
let newVueInstance = {
VERSION: '1.0',
};
const Vue = require('vue').default;
const axios_instance = axios.create({
});
Vue.prototype.$axios = axios_instance;
newVueInstance = new Vue();
return newVueInstance;
});
}());
I want to turn it into vue 3. The code is below. require('vue').default is undefined.
(function () {
define('newVueInstance', ['axios'], (axios) => {
const newVueInstance = {
VERSION: '1.0',
};
// const Vue = require('vue').default; // undefined
const Vue = require('vue');
const axios_instance = axios.create({
});
const app = Vue.createApp();
console.log('********', require('vue'));
console.log('Vue', Vue);
app.config.globalProperties.$axios = axios;
return require('vue');
// return newVueInstance;
});
}());
```.
It doesn't work.

First issue comes with Vue 3 is not exactly APM compatible which means the browser side require.js will not work.
Second is Vue 3 does not export a default. One needs to create a createApp instance.

Related

pass variable to nodesjs to localhost

I want to pass the variable "valor_dollar" into the server localhost or an file html. Actually I can not to look the variable the browser.
const express = require ('express');
const cheerio = require ('cheerio')
const request = require ('request-promise')
const axios = require('axios')
const app = express();
app.get('/',(req,res) => {
res.end(prova());
});
app.listen(3000);
function prova(){
axios.get('https://www.morningstar.es/es/funds/snapshot/snapshot.aspx?id=F0GBR04ASX').then((response) => {
// Load the web page source code into a cheerio instance
const $ = cheerio.load(response.data)
// The pre.highlight.shell CSS selector matches all `pre` elements
// that have both the `highlight` and `shell` class
const urlElems = $('td.line.text')[0]
const urlText = $(urlElems).text()
let valor_dollar = Number(urlText.substring(4,7))
console.log(valor_dollar)
})
}
You are calling res.end method directly without setting the body, the prova function returns undefined.
Instead you can modify your method like this to have a callback that runs after the HTTP call.
function prova(callback){
axios.get('https://www.morningstar.es/es/funds/snapshot/snapshot.aspx?id=F0GBR04ASX').then((response) => {
// Load the web page source code into a cheerio instance
const $ = cheerio.load(response.data)
// The pre.highlight.shell CSS selector matches all `pre` elements
// that have both the `highlight` and `shell` class
const urlElems = $('td.line.text')[0]
const urlText = $(urlElems).text()
let valor_dollar = Number(urlText.substring(4,7))
callback(valor_dollar);
});
}
and the route should be like this:
app.get('/',(req,res) => {
prova(function(value) {
res.body = { dollar_value: value };
res.end();
});
});

Can I force SSR for a Nuxt page?

In a Nuxt app I need to render a page with a lot of data displayed on a google map, obtained from a 100MB .jsonl file. I'm using fs.createReadStream inside asyncData() to parse the data and feed it to the Vue component. Since fs is a server-side only module, this means my app errors when it attempts to render that page client-side.
I would like it so this specific page will exclusively be rendered with SSR so I can use fs in the Vue component.
I thought of using a custom Express middleware to process the data, but this still results in downloading dozens of MB to the client, which is unacceptable. You can see how I request it with Axios in my example.
async asyncData( {$axios} ) {
const fs = require('fs');
if (process.server) {
console.log("Server");
async function readData() {
const DelimiterStream = require('delimiter-stream');
const StringDecoder = require('string_decoder').StringDecoder;
const decoder = new StringDecoder('utf8');
let linestream = new DelimiterStream();
let input = fs.createReadStream('/Users/Chibi/WebstormProjects/OPI/OPIExamen/static/stream.jsonl');
return new Promise((resolve, reject) => {
console.log("LETS GO");
let data = [];
linestream.on('data', (chunk) => {
let parsed = JSON.parse(chunk);
if (parsed.coordinates)
data.push({
coordinates: parsed.coordinates.coordinates,
country: parsed.place && parsed.place.country_code
});
});
linestream.on('end', () => {
return resolve(data);
});
input.pipe(linestream);
});
}
const items = await readData();
return {items};
} else {
console.log("CLIENT");
const items = this.$axios.$get('http://localhost:3000/api/stream');
return {items };
}
}
Even when it renders correctly, NUXT will show me an error overlay complaining about the issue.

Can I get createSagaMiddleware using require?

I'm trying to use run sagas in an a node app that will run from the command line: node app.js
I can't use import, so I'm trying to get createSagaMiddleware using require:
const sagaMiddleware = createSagaMiddleware()
I get this error:
"TypeError: createSagaMiddleware is not a function"
Can Saga be used like this?
const { createStore, combineReducers, applyMiddleware } = require("redux");
const createSagaMiddleware = require("redux-saga");
const { take } = require("redux-saga/effects");
const sagaMiddleware = createSagaMiddleware();
const reducer = state => state;
const store = createStore(
reducer,
applyMiddleware(sagaMiddleware)
);
function* watcherSaga() {
yield take("START");
yield //do stuff
}
sagaMiddleware.run(watcherSaga)
store.dispatch({type: 'START'})
Try this:
const createSagaMiddleware = require("redux-saga").default;

Execute a middleware one-time only at server startup in Koa v2

I created this middleware which executing only once when any route in the website gets the first hit from a visitor:
// pg-promise
const db = require('./db/pgp').db;
const pgp = require('./db/pgp').pgp;
app.use(async (ctx, next) => {
try {
ctx.db = db;
ctx.pgp = pgp;
} catch (err) {
debugErr(`PGP ERROR: ${err.message}` || err);
}
await next();
});
// One-Time middleware
// https://github.com/expressjs/express/issues/2457
const oneTime = (fn) => {
try {
let done = false;
const res = (ctx, next) => {
if (done === false) {
fn(ctx, next);
done = true;
}
next();
};
return res;
} catch (err) {
debugErr(`oneTime ERROR: ${err.message}` || err);
}
};
const oneTimeQuery = async (ctx) => {
const result = await ctx.db.proc('version', [], a => a.version);
debugLog(result);
};
app.use(oneTime(oneTimeQuery));
This code executing on the first-time only when a user visiting the website, resulting:
app:log Listening on port 3000 +13ms
app:req GET / 200 - 24ms +2s
23:07:15 connect(postgres#postgres)
23:07:15 SELECT * FROM version()
23:07:15 disconnect(postgres#postgres)
app:log PostgreSQL 9.6.2, compiled by Visual C++ build 1800, 64-bit +125ms
My problem is that I want to execute it at the server start, when there's no any visit on the site.
The future purpose of this code will be to check the existence of tables in the database.
Solution:
Placing this in ./bin/www before the const server = http.createServer(app.callback()); declaration helped:
const query = async () => {
const db = require('../db/pgp').db;
const pgp = require('../db/pgp').pgp;
const result = await db.proc('version', [], a => a.version);
debugLog(`www: ${result}`);
pgp.end(); // for immediate app exit, closing the connection pool (synchronous)
};
query();
You could start your application using a js script that requires your app and uses node's native http module to fire up the server. Exactly like in koa-generator (click).
This is in your app.js file:
const app = require('koa')();
...
module.exports = app;
And then this is in your script to fire up the server:
const app = require('./app');
const http = require('http');
[this is the place where you should run your code before server starts]
const server = http.createServer(app.callback());
server.listen(port);
Afterwards you start your application with:
node [script_name].js
Of course keep in mind the async nature of node when doing it this way. What I mean by that - run the 'listen' method on 'server' variable in callback/promise.

how to configure newrelic on node + koa app

I have an application using node.js, koa, koa-router.
I want to add newrelic to my application, but it does not support koa.
So I tried to utilise koa-newrelic (https://github.com/AfterShip/koa-newrelic) but it still does not work.
i still get /* for all transactions.
who have experience about this?
my colleague helps me to solve this issue.
the solution is below
1.declare custom koa new relic here
//****************** myKoaNewRelic.js *****************
'use strict'
module.exports = function monitor(router, newrelic) {
return function* monitor(next) {
const route = this.params[0]
for (const layer of router.stack) {
if (layer.path !== '(.*)') {
const method = (layer.methods.indexOf('HEAD') !== -1) ? layer.methods[1] : layer.methods[0]
if (route.match(layer.regexp) && method === this.request.method) {
newrelic.setControllerName(layer.path, method)
}
}
}
yield next
}
}
2.update main index.js like this
//****************** index.js *****************
'use strict'
const newrelic = require('newrelic')
const koaNewrelic = require('./myKoaNewRelic')
const app = require('koa')()
const router = require('koa-router')()
router.use(koaNewrelic(router, newrelic))
// DO SOME STUFF

Resources