Azure App Insights recommends using their react plugin for SPAs. https://learn.microsoft.com/en-us/azure/azure-monitor/app/javascript-react-plugin
In the documented example, they manually create a browser history to pass to the extension.
// AppInsights.js
import { ApplicationInsights } from '#microsoft/applicationinsights-web';
import { ReactPlugin } from '#microsoft/applicationinsights-react-js';
import { createBrowserHistory } from 'history';
const browserHistory = createBrowserHistory({ basename: '' });
const reactPlugin = new ReactPlugin();
const appInsights = new ApplicationInsights({
config: {
instrumentationKey: 'YOUR_INSTRUMENTATION_KEY_GOES_HERE',
extensions: [reactPlugin],
extensionConfig: {
[reactPlugin.identifier]: { history: browserHistory }
}
}
});
appInsights.loadAppInsights();
export { reactPlugin, appInsights };
However, I'm using react router 6, which I assume creates its own browser history. The documentation does make reference to the react router documentation, however, this is for react router 5, which does expose the history directly.
With react router 6, what would be the right way to access to the history created by the router?
This issue is discussed in great length on the following pull request [v6] Add <HistoryRouter> for standalone history objects. At a high-level, it should allow you to create a Router object with an external history object similar to the v5 documentation.
Currently, you best bet is to import the HistoryRouter component from the pull request into your own project so you can create and use an standalone history object for app insights.
I found the documentation through this question so thought it might be worth mentioning here that it has been updated to specifically address react-router v6:
https://learn.microsoft.com/en-us/azure/azure-monitor/app/javascript-react-plugin
For react-router v6 or other scenarios where router history is not
exposed, appInsights config enableAutoRouteTracking can be used to
auto track router changes
As per this github issue, page view duration data is lost as a result.
Related
I implemented a project for test purpose with restify framework in node and implemented a GET API.
But I don't know how to integrate a swagger with restify framework.
There are many blogs for integration swagger with express..
I followed a link like
https://www.npmjs.com/package/restify-swagger-jsdoc
https://github.com/bvanderlaan/swagger-ui-restify
Please help me how to integrate.
For everyone who's come this far, as well as me, I assume you're using restify instead of express and haven't found an easy answer yet. I have an API server using restify, use typescript to program and convert the files to javascript before running my server, all in a Docker container. After a lot of searching I managed to solve my problem as follows:
Install the "swagger-autogen" package.
Create a file called "swagger.ts" with the following commands:
const swaggerAutogen = require('swagger-autogen')()
const outputFile = '../swagger_output.json'
const endpointsFiles = ['../routes/users.router.ts'] // root file where the route starts.
swaggerAutogen(outputFile, endpointsFiles)
.then(() => {
require('./dist/src/app.js') // Your project's root file
})
Go to the files reserved for your API routes (where they have the GET, POST, PATCH, ... functions) -- in my case '../routes/users.router.ts', and put comments, like :
// #swagger.path = "/users"
// #swagger.tags = ['User']
// #swagger.description = 'Endpoint to create a user.'
/*
#swagger.responses[201] = {
schema: { "$ref": "#/definitions/User" },
description: "User was successfully created." }
*/
NOTE: To learn more about these swagger-autogen comment tags see:
https://github.com/davibaltar/swagger-autogen#swagger-20
Run the following command: (In my case, this command is in a script in package.json that is called inside the Dockerfile):
NOTE: Remember that if you don't automatically generate the javascript files from the script in typescript you need to create your structure entirely in javascript and not in typescript. Pay attention to file names and extensions.
node ./dist/src/server/swagger.js // change to your path
When you do this a swagger_output.json file will be created containing your application details.
After the file has been generated, you need to install the "swagger-ui-restify" package.
Put these commands where the middlewares are (usually at application startup):
const swaggerUi = require("swagger-ui-restify")
const swaggerDocument = require("../swagger_output.json")
const swaggerOptions = {
explorer: true,
baseURL: 'api-docs',
}
app.get("/api-docs"+'/*', ...swaggerUi.serve)
app.get("/api-docs", swaggerUi.setup(swaggerDocument, swaggerOptions))
Now your application has a middleware to consult the automatically generated documentation.
I connected an express api to the nuxt servermiddleware: ['~/api/index'] in the nuxt.config.js file. but if i'm dev building my api, i don't want to reload the dev server manually every single time i change something in the code (that costs a lot of time). It looks like the api runs independent from the nuxt.js website. if the website reloads, the api won't and the changes will not show. Is there a way that the api reloads when the website reloads?
my code in the index.js of the api is this:
const express = require('express')
const app = express()
const bodyParser = require("body-parser")
app.use(bodyParser.json())
// Require API routes
const company = require('./routes/company')
// Import API Routes
app.use('/company', company)
// Export the server middleware
module.exports = {
path: '/api',
handler: app
}
i hope its more clear now.
In the components folder edit your config to be like
{
// this avoids reloading all components every time you run the app
components: false
}
I have a Aurelia app that I host in an Azure app service. I would like to configure the api endpoint that Aurelia connects to by defining it in a Application Setting. How can I read that setting inside Aurelia?
As the other answers and comments also mentioned, Aurelia runs as a clientside application and has no knowledge of backend-driven applications. So the concept of something like the web.config or appsettings.json is not available here without some serious hacks. You don't want to go there.
That being said, of course you can! :) You can pretty much define any settings file you like, similar to the concept of appsettings.json of ASP.NET (Core) apps but then in Aurelia.
A great example for this is the Aurelia open source plugin Aurelia-Configuration.
Simple instructions are that your first start by adding any .json file you like (like config.json) to your project. Next, register it in your Aurelia startup:
export function configure(aurelia) {
aurelia.use
.standardConfiguration()
.developmentLogging()
.plugin('aurelia-configuration'); // <-- there you go
aurelia.start().then(a => a.setRoot());
}
Finally, just read out the values using AureliaConfiguration. The sample below illustrates it with dependency injection:
import {inject} from 'aurelia-framework';
import {AureliaConfiguration} from 'aurelia-configuration';
#inject(AureliaConfiguration)
export class MyComponent {
constructor(config) {
this.config = config;
this.config.get('endpoint');
}
}
The README explains it all.
Note: I'm not affiliated with the aurelia-configuration plugin, but just a fan of it.
Isn't Aurelia a JavaScript client framework, e.g. all-in-browser no backend? Application Settings is a server side thing (key-value store) in App Service. No backend, no app settings.
Consider this restify minimal backend that returns Application Settings by calling /settings/{app-setting-name}:
var restify = require('restify');
function respond(req, res, next) {
// Returns app setting value.
// Provides zero input validation,
// DO NOT COPY PASTE INTO PROD,
// ALL YOUR BASE WILL BELONG TO US.
res.send(process.env[req.params.setting]);
next();
}
var server = restify.createServer();
server.get('/settings/:setting', respond);
server.head('/settings/:setting', respond);
server.listen(process.env.PORT || 3000, function() {
console.log('restify listening...');
});
Hope this all makes more sense now.
I am using Mobx and mobx-model for state management in my React app. I am not doing server-side render as of now. But, I have a scenario where I need to use my model in the server side.
An example model in my project is shown below.
import { API, BaseModel } from "mobx-model";
class UserModel extends BaseModel {
...
static loadAll() {
...
}
}
The above model works fine in the client (in the browser). But, I have a scenario where I need to call the loadAll method from the server.
If I require this model from the server side as follows, I get an error.
const { UserModel } = require("../../src/models/models");
The error message is:
SyntaxError: Unexpected token import
Any idea how I can fix this to work on the server side?
I found a solution to this problem. Instead of requiring the UserModel, I could require the API from mobx-model as follows:
const { API } = require("mobx-model");
I could use the API from the server without much code changes. I have to rewrite a little bit of loadAll logic again in the server. That works for me for now.
I'm trying to get google calendar events into my React Redux app.
I've tried using googleapis and google-auth-library but webpack is throwing errors because googleapis was built to run server side and bundle.js is referenced from client.
So I've read a few forums about these errors and they all point to using Google's js client library instead.
I understand how to implement this in a java or php app (I'm old... 35 ;) but I'm new to React Redux and I'm looking for the best way to implement this.
I'm trying to fetch the events from my calendar in my actions.js. I tried including <script src="https://apis.google.com/js/api.js"></script> in my html header and then using gapi.load() from actions.js. I also tried creating a api.js file and referencing that with require('./api'). I also tried to use the cli commands from the Node.js Quickstart guide to get an access_token and then just use axios to call Google API directly but I'm getting a 403. I'm thinking I'm just not providing the proper headers but that wouldn't be best practice anyway.
My question is basically how do I reference Google's js client library from my actions.js file while adhering to Redux standards?
You're on the right track by including the official Google client API in the HTML header. It's less than ideal -- it would be nice if Google provided the (browser) client API as an npm module that you could import. But they don't (that I see), so I think what you're doing is fine.
Then there's the question of "how do I use it in a way that's React/Redux friendly?" Redux is a mechanism for managing the state of your application. The Google API is not part of your application (though what you do with it may inform the state of your application).
It's easy to verify that you have access to the Google API: you can just make a call from the componentDidMount method of one of your components, and do a console log:
class MyComp extends React.Component {
componentDidMount() {
// this is taken directly from Google documentation:
// https://developers.google.com/api-client-library/javascript/start/start-js
function start() {
// 2. Initialize the JavaScript client library.
gapi.client.init({
'apiKey': 'YOUR_API_KEY',
// clientId and scope are optional if auth is not required.
'clientId': 'YOUR_WEB_CLIENT_ID.apps.googleusercontent.com',
'scope': 'profile',
}).then(function() {
// 3. Initialize and make the API request.
return gapi.client.request({
'path': 'https://people.googleapis.com/v1/people/me',
})
}).then(function(response) {
console.log(response.result);
}, function(reason) {
console.log('Error: ' + reason.result.error.message);
});
};
// 1. Load the JavaScript client library.
gapi.load('client', start);
},
}
If you don't see what you expect on the console, somehow gapi isn't getting loaded as you expect. If that happens, you'll have a more specific question you can ask!
If you do get a response, you now know how to call GAPI...but then how to make use of it in a Redux-friendly way?
When you make a GAPI call, you probably want to modify your application's state in some way (otherwise why would you be doing it?) For example, you might invoke the auth flow, and when GAPI returns success, your application state now has loggedIn: true or similar (possibly with lots of other state changes). Where you make the GAPI call is up to you. If you want to do it when the component loads, you should do it in componentDidMount. You also may commonly be making the GAPI call in response to a user action, such as clicking on a button.
So the typical flow would be something like this:
// either in componentDidMount, or a control handler, usually:
someGapiCall()
.then(result => {
this.props.onGapiThing(result.whatever)
})
Where this.props.onGapiThing is a function that dispatches an appropriate action, which modifies your application state.
I hope this overview helps...feel free to follow up with more specific questions.
Can you try this library which I used to load external libraries and modules in my React app when I couldn't find a NPM module for it:
https://github.com/ded/script.js/
So your code will be like this:
import $script from 'scriptjs';
$script('https://apis.google.com/js/api.js', function () {
//Put your google api functions here as callback
});
I'm going to answer my own question despite some very good correct answers.
#MattYao answered my actual question of how to get a js script available for reference in my actions.js file.
#Ethan Brown gave a very detailed answer that showed some excellent flow possibilities.
#realseanp changed the scope but a valid answer.
I tried all of the above and they worked.
So I'm not sure what I was doing wrong but I was finally able to access the gapi object from actions.js by just adding <script src="https://apis.google.com/js/api.js"></script> to my index head.
I'm using pug so it looks like this:
doctype
html
head
title MyTitle
link(rel='stylesheet' href='/static/css/main.css')
link(rel='stylesheet' href='/static/css/react-big-calendar.css')
script(src='https://apis.google.com/js/api.js' type='text/javascript')
body
div(id='app')
script(src='/static/bundle.js' type='text/javascript')
Here is my component file:
import React from 'react'
import BigCalendar from 'react-big-calendar';
import moment from 'moment';
import { connect } from 'react-redux'
import { fetchEvents } from '../actions/actions'
BigCalendar.momentLocalizer(moment);
#connect((store) => {
return {
events: store.events.events
}
})
export default class Calendar extends React.Component
{
componentWillMount()
{
this.props.dispatch(fetchEvents())
}
render()
{
return (
<div>
<BigCalendar
events={this.props.events}
startAccessor='startDate'
endAccessor='endDate'
style={{height: 800}}
/>
</div>
)
}
}
And then I was able to get this working in my actions.js file
export function fetchEvents()
{
return (dispatch) =>
{
function start()
{
// 2. Initialize the JavaScript client library.
gapi.client.init({
'apiKey': API_KEY,
// clientId and scope are optional if auth is not required.
'clientId': CLIENT_ID,
'scope': 'profile',
}).then(function() {
// 3. Initialize and make the API request.
return gapi.client.request({
'path': 'https://www.googleapis.com/calendar/v3/calendars/MY_EMAIL#gmail.com/events?timeMax=2017-06-03T23:00:00Z&timeMin=2017-04-30T00:00:00Z',
})
}).then( (response) => {
let events = response.result.items
dispatch({
type: 'FETCH_EVENTS_FULFILLED',
payload: events
})
}, function(reason) {
console.log(reason);
});
};
// 1. Load the JavaScript client library.
gapi.load('client', start)
}}
I had to make my calendar public to access it this way. So now I'm going to work on the oauth2 stuff :/
I would load all the google stuff in my index file before i loaded my webpack bundle (Option 1) . Then I would use redux sagas to call the google apis. Loading the google code before your webpack bundle will ensure everything is ready to go when you call the api from the saga
Try this package.
It looks like it is updated.
https://github.com/QuodAI/tutorial-react-google-api-login