How to get the component name from a Proxy in Vue - vue.js

I'm implementing onErrorCaptured in a Vue component. It has 3 parameters (error: unknown, instance: ComponentPublicInstance, info: string). instance actually ends up being a Proxy. Since the error bubbles up to the component that I'm implementing the onErrorCaptured in, I am trying to get the name of the component that threw the error.
I'm pretty sure that using the router will work in most cases const throwingComponentName = router.currentRoute.value.name.
However, how do I get the name of the component from the instance?

If your component has its name option defined, you can access it from instance._.type.name:
onErrorCaptured((err, instance, info) => {
console.log('component name', instance._?.type?.name)
})
demo
Since instance._ is technically an internal/undocumented property, use it with caution, as it could be refactored/removed in a future release. This works as of vue#3.2.37.

Related

Raku Cro service subscribing to data "in the background" general guidance

I am attempting to put together a Cro service that has a react/whenever block consuming data "in the background" So unlike many examples of websocket usage with Cro, this has nothing to do with routes that may be accessed via the browser.
My use case is to consume message received via an MQTT topic and do some processing with them. At a later stage in development I might create a supply out of this data, but for now, when data is received it will be stored in a variable and dependant on certain conditions, be sent to another service via a http post.
My thought was to include a provider() in the Cro::HTTP::Server setup like so:
use Cro::HTTP::Log::File;
use Cro::HTTP::Server;
use Routes;
use DataProvider; # Here
my Cro::Service $http = Cro::HTTP::Server.new(
http => <1.1>,
host => ...,
port => ...,
application => [routes(), provider()], # Made this into an array of subs?
after => [
Cro::HTTP::Log::File.new(logs => $*OUT, errors => $*ERR)
]
);
And in the DataProvider.pm6:
use MQTT::Client;
sub provider() is export {
my $mqtt = MQTT::Client.new: server => 'localhost';
react {
whenever $mqtt.subscribe('some/mqtt/topic') {
say "+ topic: { .<topic> } => { .<message>.decode("utf8-c8") }";
}
}
}
This throws a bunch of errors:
A react block:
in sub provider at DataProvider.pm6 (DataProvider) line 5
in block <unit> at service.p6 line 26
Died because of the exception:
Invocant of method 'write' must be an object instance of type
'IO::Socket::Async', not a type object of type 'IO::Socket::Async'. Did
you forget a '.new'?
in method subscribe at /home/cam/raku/share/perl6/site/sources/42C762836A951A1C11586214B78AD34262EC465F (MQTT::Client) line 133
in sub provider at DataProvider.pm6 (DataProvider) line 6
in block <unit> at service.p6 line 26
To be perfectly honest, I am totally guessing that this is how I would approach the need to subscribe to data in the background of a Cro service, but I was not able to find any information on what might be considered the recommended approach.
Initially I had my react/whenever block in the main service.pm6 file, but that did not seem right. And needed to be wrapped in a start{} block because as I have just learned, react is blocking :) and cro was not able to actually start.
But following the pattern of how Routes are implemented seemed logical, but I am missing something. The error speaks about setting up a new method, but I'm not convinced that is the root cause. Routes.pm6 does not have a constructor.
Can anyone point me in the right direction please?
Thanks to all who have provided information, this has been a very valuable learning exercise.
The approach of passing additional sub routines, along side router() in the application parameter to Cro::HTTP::Server.new gave further trouble. (an array is not allowed, and broke routing)
Instead, I have moved the background work into a class of it's own, and given it a start and stop method more akin to Cro::HTTP::Server.
My new approach:
service.pm6
use Cro::HTTP::Log::File;
use Cro::HTTP::Server;
use Routes;
use KlineDataSubscriber; # Moved mqtt functionality here
use Database;
my $dsn = "host=localhost port=5432 dbname=act user=.. password=..";
my $dbh = Database.new :$dsn;
my $mqtt-host = 'localhost';
my $subscriber = KlineDataSubscriber.new :$mqtt-host;
$subscriber.start; # Inspired by $http.start below
my Cro::Service $http = Cro::HTTP::Server.new(
http => <1.1>,
host => ...,
port => ...,
application => routes($dbh), # Basically back the way it was originally
after => [
Cro::HTTP::Log::File.new(logs => $*OUT, errors => $*ERR)
]
);
$http.start;
say "Listening at...";
react {
whenever signal(SIGINT) {
say "Shutting down...";
$subscriber.stop;
$http.stop;
done;
}
}
And in KlineDataSubscriber.pm6
use MQTT::Client;
class KlineDataSubscriber {
has Str $.mqtt-host is required;
has MQTT::Client $.mqtt = Nil;
submethod TWEAK() {
$!mqtt = MQTT::Client.new: server => $!mqtt-host;
await $!mqtt.connect;
}
method start(Str $topic = 'act/feed/exchange/binance/kline-closed/+/json') {
start {
react {
whenever $!mqtt.subscribe($topic) {
say "+ topic: { .<topic> } => { .<message>.decode("utf8-c8") }";
}
}
}
}
method stop() {
# TODO Figure how to unsubscribe and cleanup nicely
}
}
This feels much more "Cro idiomatic" to me, but I would be happy to be corrected.
More importantly, it works as expected and I feel is somewhat future proof. I should be able to create a supply to make real-time data available to the router, and push data to any connected web clients.
I also intend to have a http GET endpoint /status with various checks to ensure everything healthy
The root cause
The error speaks about setting up a new method, but I'm not convinced that is the root cause.
It's not about setting up a new method. It's about a value that should be defined instead being undefined. That typically means a failure to attempt to initialize it, which typically means a failure to call .new.
Can anyone point me in the right direction please?
Hopefully this question helps.
Finding information on a recommended approach
I am totally guessing that this is how I would approach the need to subscribe to data in the background of a Cro service, but I was not able to find any information on what might be considered the recommended approach.
It might be helpful for you to list which of the get-up-to-speed steps you've followed from Getting started with Cro, including the basics but also the "Learn about" steps at the end.
The error message
A react block:
in sub provider ...
Died because of the exception:
...
in method subscribe ...
The error message begins with the built in react construct reporting that it caught an exception (and handled it by throwing its own exception in response). A "backtrace" corresponding to where the react appeared in your code is provided indented from the initial "A react block:".
The error message continues with the react construct summarizing its own exception (Died because ...) and explains itself by reporting the original exception, further indented, in subsequent lines. This includes another backtrace, this time one corresponding to the original exception, which will likely have occurred on a different thread with a different callstack.
(All of Raku's structured multithreading constructs[1] use this two part error reporting approach for exceptions they catch and handle by throwing another exception.)
The first backtrace indicates the react line:
in sub provider at DataProvider.pm6 (DataProvider) line 5
use MQTT::Client;
sub provider() is export {
my $mqtt = MQTT::Client.new: server => 'localhost';
react {
The second backtrace is about the original exception:
Invocant of method 'write' must be an object instance of type
'IO::Socket::Async', not a type object of type 'IO::Socket::Async'. ...
in method subscribe at ... (MQTT::Client) line 133
This reports that the write method called on line 133 of MQTT::Client requires its invocant is an instance of type 'IO::Socket::Async'. The value it got was of that type but was not an instance, but instead a "type object". (All values of non-native types are either type objects or instances of their type.).
The error message concludes with:
Did you forget a '.new'?
This is a succinct hint based on the reality that 99 times out of a hundred the reason a type object is encountered when an instance is required is that code has failed to initialize a variable. (One of the things type objects are used for is to serve the role of "undefined" in languages like Perl.)
So, can you see why something that should have been an initialized instance of 'IO::Socket::Async' is instead an uninitialized one?
Footnotes
[1] Raku's constructs for parallelism, concurrency, and asynchrony follow the structured programming paradigm. See Parallelism, Concurrency, and Asynchrony in Raku for Jonathan Worthington's video presentation of this overall approach. Structured constructs like react can cleanly observe, contain, and manage events that occur anywhere within their execution scope, including errors such as error exceptions, even if they happen on other threads.
You seem to be fine now but when I first saw this I made this https://github.com/jonathanstowe/Cro-MQTT which turns the MQTT client into a first class Cro service.
I haven't released it yet but it may be instructive.

Recommended dynamic runtime configuration technique on nuxtjs (other than dotenv)

I have been trying to use publicRuntimeConfig / privateRuntimeConfig
On nuxt 2.4.1, I have defined my runtime config as follows on nuxt.config.js
publicRuntimeConfig: {
DATA_API_HOST_URL: process.env.VUE_APP_DATA_API_HOST_URL,
},
privateRuntimeConfig: {
AUTH_APP_CLIENT_SECRET: process.env.VUE_APP_AUTH_APP_CLIENT_SECRET,
},
and calling it as follows on my login.vue
asyncData( ctx ) {
console.log(ctx.$config.DATA_API_HOST_URL)
//some activity
}
The keys are showing up on $config inside asyncData. I debugged on chrome dev tools. But value is not read from process.env.VUE_APP_DATA_API_HOST_URL. The value is showing up as undefined. However, process.env.VUE_APP_DATA_API_HOST_URL is showing the value OK. The whole point is to move away from process.env.
this.$config.DATA_API_HOST_URL also does not access the values.
'${DATA_API_HOST_URL}' is shown in examples but I believe it is only for explicit param declarations at asyncData like asyncData( { $config : {DATA_API_HOST_URL}).
When I pass values as it is using DATA_API_HOST_URL: process.env.VUE_APP_DATA_API_HOST_URL || 'https://test.api.com', it seems to copy the value fine using ctx.$config.DATA_API_HOST_URL!
Looking to me like copying process.env to *RuntimeConfig has a problem!
What is the recommended way of importing and using runtime configurations?
As per documentation in the Nuxt blog post you marked, the feature your are trying to use is released in 2.13 (you´re using 2.4 if i not misunderstood). That could be the reason behind the behaviour you're seeing.
I'd recommend update your project dependencies or trying another approach.
I think you should use Docker to set dynamic runtime config like link below:
https://dev.to/frontendfoxes/dockerise-your-nuxt-ssr-app-like-a-boss-a-true-vue-vixens-story-4mm6

How to share a variable between two routers module in cro?

I try to use Cro to create a Rest API that will publish messages in rabbitMQ. I would like to split my routes in different modules and compose them with an "include". But I would like to be able to share the same connection to rabbitMQ in each of those modules too. I try with "our" but it does not work :
File 1:
unit module XXX::YYY;
use Cro::HTTP::Router;
use Cro::HTTP::Server;
use Cro::HTTP::Log::File;
use XXX::YYY::Route1;
use Net::AMQP;
our $rabbitConnection is export = Net::AMQP.new;
await $rabbitConnection.connect;
my $application = route {
include <api v1 run> => run-routes;
}
...
File 2:
unit module XXX::YYY::Route1;
use UUID;
use Cro::HTTP::Router;
use JSON::Fast;
use Net::AMQP;
my $channel = $XXX::YYY::rabbitConnection.open-channel().result;
$channel.declare-queue("test_task", durable=> True );
sub run-routes() is export { ... }
Error message:
===SORRY!===
No such method 'open-channel' for invocant of type 'Any'
Thanks!
When you define your exportable route function you can specify arguments then in your composing module you can create the shared objects and pass them to the routes. For example in your router module :
sub run-routes ($rmq) is export{
route {
... $rmq is available in here
}
}
Then in your main router you can create your Queue and pass it in when including
my $rmq = # Insert queue creation code here
include product => run-routes( $rmq );
I've not tried this but I can't see any reason why it shouldn't work.
The answer by #Scimon is certainly correct, but it does not addresses the OP. On the other hand, the two comments by #ugexe and #raiph are spot-on, so I'll try to summarize them here and explain what's going on.
The error itself
This is the error:
Error message:
===SORRY!=== No such method 'open-channel' for invocant of type 'Any'
It indicates the invocant ($XXX::YYY::rabbitConnection) is of type Any, which is the type usually assigned to variables when they don't have a defined value; that is, basically, $XXX::YYY::rabbitConnection is not defined. It certainly is not since XXX::YYY is not included among the imported modules, as indicated by #ugexe.
The additioal problem indicated by the OP
That module was eliminated from the imported list because, as indicated by the OP
I certainly code it the wrong way because if i try to add use
XXX::YYY;, i get a Circular module loading detected error
But of course. since use XXX::YYY::Route1; which is file 2, is included in File 1.
The final solution is to reorganize files
That circular dependence probably points out to the fact that they should be in the same file, or else common code should be factored out to a third file, which would be eventually be included by both. So you should have something like
unit module XXX::YYY::Common;
use Net::AMQP;
our $rabbitConnection is export = Net::AMQP.new;
await $rabbitConnection.connect;
And then
use XXX::YYY::Common;
in both modules.

How to use module.exports and requireJS?

im quite a noob in html and js, so forgive me if this is a dumb question but, im trying to use requireJs to export modules in node and i can't get the function work right.
here is the code extracted from example.
first i have this main.js, as the note in the documentation says http://requirejs.org/docs/node.html#2
var sayHi = require(['./greetings.js'], function(){});
console.log(sayHi);
and a greetings.js who export the answer
module.exports= 'Hello';
});
and get nothing as result, so i define the exports and modules
define( function(exports,module){
module.exports= 'Hello';
});
and get as result:
function localRequire()
what am i doing wrong? i read the documentation and examples, but somehow i can't make this works.
I'm assuming the require call you are using is RequireJS's require call, not Node's require. (Otherwise, you'd get a very different result.)
You are using the asynchronous form of the require call. With the asynchronous form, there is no return value for you to use, you have to use the callback to get module values, like this:
require(['./greetings.js'], function(sayHi){
console.log(sayHi);
});
However, because you are running in Node, you can do this:
var sayHi = require('./greetings.js');
Note how the first argument is a string, not an array of dependencies. This is the synchronous form of the require call. The returned value is the module you required. When you are in Node, RequireJS allows you to call this synchronous form anywhere. When you are running the browser, it is only available inside a define call.

Running multiple browser instances in the same test spec

If I have a single spec that is using page object model, how do I run multiple browser instance for that same spec?
For example I have spec:
it('should run multi browser', function() {
browser.get('http://example.com/searchPage');
var b2 = browser.forkNewDriverInstance();
b2.get('http://example.com/searchPage');
var b3 = browser.forkNewDriverInstance();
b3.get('http://example.com/searchPage');
SearchPage.searchButton.click();
b2.SearchPage.searchButton.click(); //fails here
b3.SearchPage.searchButton.click();
});
How do I reuse vars declared in the SearchPage page object for the other browser instances?
This is a really interesting question that is not covered in Using Multiple Browsers in the Same Test or in the interaction_spec.js.
The problem with page objects is that page object fields are usually defined with a globally available element or browser which in your case would always point to the first browser instance. But you basically need to call element() using a specific browser:
b2.element(by.id('searchInput'));
instead of just:
element(by.id('searchInput'));
FYI, element is just a shortcut for browser.element.
I am really not sure whether this is a reliable solution and would actually work, but you can redefine global element this way. Think about it as switching the search context to different browser instances:
SearchPage.searchButton.click();
global.element = b2.element;
SearchPage.searchButton.click();
global.element = b3.element;
SearchPage.searchButton.click();
global.element = browser.element;