Can Breeze.js be optimized with r.js? - breeze

I have a SPA that makes use of the breeze.js library. I am using require.js to load modules. I want to optimize the application into a single JavaScript file using r.js, however I am getting the following error:
Tracing dependencies for: main
Error: ../Scripts/breeze.debug.js has two many anonymous modules in it.
at ...\Scripts\r.js:20154:35
Am I barking up the wrong tree trying to optimize with r.js? I can't see anything on the breeze.js site site to indicate that it can or can not be done.
Cut down version of m main.js:
require.config({
paths: {
"jquery": "../Scripts/jquery-1.9.1",
"Q": "../Scripts/q",
"breeze": "../Scripts/breeze.debug"
},
shim: {
"breeze": {
"deps": ["Q"]
}
},
});
require(["breeze"], function (breeze) {
//do something
});
Here is the app.build.js build file:
({
baseUrl: "../App",
mainConfigFile: '../app/main.js',
name: "main",
out: "../Build/Output/main-built.js"
})

Don't know why you're getting that error.
To be honest, we are unlikely to explore why any time soon mostly because we're not convinced that merging the entire application into a single file is a goal we would pursue with much enthusiasm.
There is great value in reducing the number of script files but it's not clear that there is much value in reducing that number to one. Breeze itself is on the (ahem) larger side so you've got a pretty healthy payload for that script request alone. A browser that can ask for scripts in parallel might actually load several scripts more quickly than it could load just one big script. And, finally, you could benefit from loading Breeze from a CDN rather than as embedded material in a mondo-script file on your web server.
Still, we hate the idea that this is failing for you. If you can figure out what is going on, we'd take reasonable steps to correct it. Thanks ... from the Breeze team.

Related

Dart Functions Framework usage

I'm new to the Dart functions framework. My goal is to use this package to create several functions and deploy them to Cloud Run (in combination with Firebase, but I guess that's irrelevant to this question).
I've run the quick starts and I've read all of the contents in the docs.
The quick start mentions just one function at a time (e.g. Hello World, Cloud Events, etc..), like this:
import 'package:functions_framework/functions_framework.dart';
import 'package:shelf/shelf.dart';
#CloudFunction()
Response function(Request request) {
return Response.ok('Hello, World!');
}
But as you can see in the quickstarts only one function is handled in a project at a time. How about me wanting to deploy several functions? Should I:
Write several functions in the same project / file, so that the function framework compiles the 'server.dart` by itself
OR
Create a different functions_framework for each function?
Let me be more specific. Should I do the following (option 1 - which makes more sense to me):
import 'dart:math';
import 'package:functions_framework/functions_framework.dart';
import 'package:shelf/shelf.dart';
#CloudFunction()
Response function(Request request) {
return Response.ok('Hello, World!');
}
#CloudFunction()
Response function2(Request request) {
if (Random().nextBool()) {
return Response.ok('Hello, World!');
} else {
return Response.internalServerError();
}
}
Or should I build a different folder by running a build_runner for each function I need in my project?
Is there a difference and/or a best practice?
Thanks in advance.
EDIT. This question is related to the deployment on Cloud Run itself, and not just testing on my own PC. To test my own functions I did the following:
Run dart run build_runner build, so that it updates the server.dart file correctly (I can see that the framework does a lot behind the scenes and that the _nameToFunctionTarget is basically a router);
Run the server in two different terminals, like this: dart run bin/server.dart --port MYPORT --target MYFUNCTION (where MYPORT and MYFUNCTION are either 8080/8081 or function/function2 respectively).
I guess I'm just confused on how to correctly manage this framework once deployed on Cloud Run.
EDIT 2. I just gave up using Dart as a Serverless language or even a Backend language. There's just too much jargon even for the basic things. Any backend framework is either dead, or maintained by one single enthusiast guy (props to him!). This language has not yet received enough love from the Google Team / the community and at this moment in time is basically not possible to go fullstack on just Dart. It's a dream, but it can't be realized now. Furthermore, Dart hardly lacks a proper SDKs to use Firestore, etc., so Firebase isn't an option. I find it easier to just learn NodeJS and exploit the Firebase support for Firebase Functions written in NodeJS, and I'll wait for more support in there in the future, if there ever will be.
The documentation is a bit sparse right now (and I'm new to it also! I couldn't find any good examples, so here goes...)
You can only have a single function that is served. It should be
named 'function' (the type and name can be overriden, see the
cloudevent example dartfn generate cloudevent)
You 'could' have many of these deployed so that each does a specific thing, such as processing cloudevents above, but most people
want something more REST-like (see next)
You need to attach a Router() so that you can have the single entry point (function) handled by specific logic in your code.
Example for Rest
add to pubspec.yaml (in dependencies:) shelf_router: ^1.1.2
delegate the #CloudFunction to use the Router()
functions.dart
import 'package:functions_framework/functions_framework.dart';
import 'package:shelf/shelf.dart';
import 'package:shelf_router/shelf_router.dart';
Router app = Router()
..get('/health', (Request request) {
return Response.ok('healthy');
})
..get('/user/<user>', (Request request, String user) {
// fetch the user... (probably return as json)
return Response.ok('hello $user');
})
..post('/user', (Request request) {
// convert request body to json and persist... (probably return as json)
return Response.ok('saved the user');
});
#CloudFunction()
Future<Response> function(Request request) => app.call(request);

Workbox - Service worker index.html/asset mismatch

I have a simple service worker set up with workbox. The precache contains index.html and a main.xxx.js javascript bundle (among other things) where xxx is updated on each build. The precache setup is very simple, using workbox-build.
workboxBuild.injectManifest({
// ...
globPatterns: [
'index.html',
'main.*.js',
// ...
]
})
The problem that I'm seeing randomly (particularly in Safary and Firefox) is that the index seems to get into a bad (outdated) state where it references main.xxx.js yet the current build is on main.yyy.js, which doesn't exist and breaks the site. I can verify this by visiting Chrome which shows the correct reference to main.yyy.js in the index.html and works fine. What am I missing here and what strategy can I use to insure that I always have the same version?
To be clear, nothing seems to solve the problem once it's in a bad state. Refreshing does nothing.

How can you get information about other apps running or in focus?

My motivation: I'm writing an app to help with some quantified self / time tracking type things. I'd like to use electron to record information about which app I am currently using.
Is there a way to get information about other apps in Electron? Can you at least pull information about another app that currently has focus? For instance, if the user is browsing a webpage in Chrome, it would be great to know that A) they're using chrome and B) the title of the webpage they're viewing.
During my research I found this question:
Which app has the focus when a global shortcut is triggered
It looks like the author there is using the nodObjc library to get this information on OSX. In addition to any approaches others are using to solve this problem, I'm particularly curious if electron itself has any way of exposing this information without resorting to outside libraries.
In a limited way, yes, you can get some of this information using the electron's desktopCapturer.getSources() method.
This will not get every program running on the machine. This will only get whatever chromium deems to be a video capturable source. This generally equates to anything that is an active program that has a GUI window (e.g., on the task bar on windows).
desktopCapturer.getSources({
types: ['window', 'screen']
}, (error, sources) => {
if (error) throw error
for (let i = 0; i < sources.length; ++i) {
log(sources[i]);
}
});
No, Electron doesn't provide an API to obtain information about other apps. You'll need to access the native platform APIs directly to obtain that information. For example Tockler seems to do so via shell scripts, though personally I prefer accessing native APIs directly via native Node addons/modules or node-ffi-napi.
2022 answer
Andy Baird's answer is definitely the better native Electron approach though that syntax is outdated or incomplete. Here's a complete working code snippet, assumes running from the renderer using the remote module in a recent Electron version (13+):
require('#electron/remote').desktopCapturer.getSources({
types: ['window', 'screen']
}).then(sources => {
for (const thisSource of sources) {
console.log(thisSource.name);
}
});
The other answers here are for the rendering side - it might be helpful to do this in the main process:
const { desktopCapturer } = require('electron')
desktopCapturer.getSources({ types: ['window', 'screen'] }).then(async sources => {
for (const source of sources) {
console.log("Window: ", source.id, source.name);
}
})

Download repository from Github

I'm trying to learn Yeoman, but find the official documentation severely lacking. I've found the remote() function which appears to download a GIT repository but whatever I do I can't get it to work without throwing errors.
Here's what I have:
this.remote('powerbuoy', 'SleekWP', 'master', function (err, remote) {
if (err) {
this.log(err);
return err;
}
remote.copy('.', this.destinationPath('wp-content/themes/sleek/'));
}.bind(this));
What I'm hoping would happen here is that the https://github.com/powerbuoy/SleekWP/ repo is downloaded and moved to wp-content/themes/sleek/. What happens instead is I get:
fs.js:603
var r = binding.read(fd, buffer, offset, length, position);
^
Error: EISDIR: illegal operation on a directory, read
Is there a better documentation or a tutorial explaining all these basics somewhere? I'd love to know how to copy files without each copy being printed to the console too for example. This all seems pretty basic but http://yeoman.io/authoring/ is very sparse.
Ok, so apparently the solution was to use remote.bulkDirectory() instead of remote.copy().
Edit: However, reading the "documentation" (can barely be called that) it says that "You should never use this method, unless there's no other solution." (http://yeoman.io/generator/actions_actions.html)
So if anyone knows of the proper way to do this I'd love to know.
I switched to the fs-extra package and used cacheRoot() and destinationRoot() to copy the directory instead:
fs.copy(this.cacheRoot() + '/username/Project/branch/', this.destinationPath('destination/path/')

Using Neo4j with React JS

Can we use graph database neo4j with react js? If not so is there any alternate option for including graph database in react JS?
Easily, all you need is neo4j-driver: https://www.npmjs.com/package/neo4j-driver
Here is the most simplistic usage:
neo4j.js
//import { v1 as neo4j } from 'neo4j-driver'
const neo4j = require('neo4j-driver').v1
const driver = neo4j.driver('bolt://localhost', neo4j.auth.basic('username', 'password'))
const session = driver.session()
session
.run(`
MATCH (n:Node)
RETURN n AS someName
`)
.then((results) => {
results.records.forEach((record) => console.log(record.get('someName')))
session.close()
driver.close()
})
It is best practice to close the session always after you get the data. It is inexpensive and lightweight.
It is best practice to only close the driver session once your program is done (like Mongo DB). You will see extreme errors if you close the driver at a bad time, which is incredibly important to note if you are beginner. You will see errors like 'connection to server closed', etc. In async code, for example, if you run a query and close the driver before the results are parsed, you will have a bad time.
You can see in my example that I close the driver after, but only to illustrate proper cleanup. If you run this code in a standalone JS file to test, you will see node.js hangs after the query and you need to press CTRL + C to exit. Adding driver.close() fixes that. Normally, the driver is not closed until the program exits/crashes, which is never in a Backend API, and not until the user logs out in the Frontend.
Knowing this now, you are off to a great start.
Remember, session.close() immediately every time, and be careful with the driver.close().
You could put this code in a React component or action creator easily and render the data.
You will find it no different than hooking up and working with Axios.
You can run statements in a transaction also, which is beneficial for writelocking affected nodes. You should research that thoroughly first, but transaction flow is like this:
const session = driver.session()
const tx = session.beginTransaction()
tx
.run(query)
.then(// same as normal)
.catch(// errors)
// the difference is you can chain multiple transactions:
const tx1 = await tx.run().then()
// use results
const tx2 = await tx.run().then()
// then, once you are ready to commit the changes:
if (results.good !== true) {
tx.rollback()
session.close()
throw error
}
await tx.commit()
session.close()
const finalResults = { tx1, tx2 }
return finalResults
// in my experience, you have to await tx.commit
// in async/await syntax conditions, otherwise it may not commit properly
// that operation is not instant
tl;dr;
Yes, you can!
You are mixing two different technologies together. Neo4j is graph database and React.js is framework for front-end.
You can connect to Neo4j from JavaScript - http://neo4j.com/developer/javascript/
Interesting topic. I am using the driver in a React App and recently experienced some issues. I am closing the session every time a lifecycle hook completes like in your example. When there where more intensive queries I would see a timeout error. Going back to my setup decided to experiment by closing the driver in some more expensive queries and it looks like (still need more testing) the crashes are gone.
If you are deploying a real-world application I would urge you to think about Authentication and Authorization when using a DB-React setup only as you would have to store username/password of the neo4j server in the client. I am looking into options of having the Neo4J server issuing a token and receiving it for Authorization but the best practice is for sure to have a Node.js server in the middle with something like Passport to handle Authentication.
So, all in all, maybe the best scenario is to only use the driver in Node and have the browser always communicating with the Node server using axios...

Resources