Defer ALL Quasar initialisation so that it starts ONLY after a promise is fulfilled? - promise

I am using the Quasar environment, and WASM/emscripten for some core functions called from everywhere in my app, including in many initializations.
Unfortunately, WASM is asynchronously compiled, and nothing in my app works before this environment is ready.
This is what I would like to do:
initialize_WASM().then(()=>start_and_run_Quasar());
Is there a way to do that (boot files, hooks, index.html ...)?
Thanks!
Michel

Related

How to be sure, that web application (html/js) is open in Task Module?

I have created a message extension app for MS TEAMS. I use Task Module. And a single page application was created especially for this message extensions. It works. I just do NOT want that single page application can be opened in a browser. It should work only inside the Task Module. Is any possibility to do that?
Have a look at the Teams client SDK, especially microsoftTeams.getContext. You could do something like have your content hidden, or empty, and then only call your API/show your content/whatever, when the getContext returns.

Angular 2 events get postponed strangely when I include some other non-angular script

I have encountered a strange problem when using angular 2 beta RC.
Events get postponed if I include an external script I wrote into any angular 2 project:
<script>
(function(r,a,k,e,y,o,u){r['RakrWidgetObject']=y;r[y]=r[y]||function(){
(r[y].q=r[y].q||[]).push(arguments)},r[y].l=1*new Date();o=a.createElement(k),
u=a.getElementsByTagName(k)[0];o.async=1;o.src=e;u.parentNode.insertBefore(o,u)
})(window,document,'script','//cht.technology/rakr.js','rakr');
rakr('//localhost:3000', 'RAKR-000001');
</script>
Take github project thelgevold/angular-2-samples for example, once I add the below script as I did in https://github.com/tan9/angular-2-samples/tree/event-postponed branch.
The angular 2 application starts to behave strangely, some event changes won't be taking into account by angular until I trigger another event manually, I have to click a button twice to get correct rendering as this recording I uploaded to imgur
I don't know what's happening to the external script I wrote, it's a simple project that only depends on html2canvas and es6-promise, which can capture screenshot using html2canvas and send it to another web service. The bundle was built by webpack, and I tried to build the bundle by using browersify, with no luck.
This is a caveat with how Zone.js works. Zone.js patches async browser events and provides an API in which Angular uses to determine when changes happen and when to run change detection in order to update the UI.
In the case of your third-party library that uses the browser Promise API, it needs to be loaded before Zone.js is loaded via script tag. This is so that async events are patched so it will be run in the "zone" that Angular runs in. Events running outside the zone won't be picked up unless change detection is run manually, or the event is run in the context of the Angular zone.
As explained by brandon, make the code run inside Angulars zone
inject NgZone
constructor(private ngZone:NgZone){}
...
this.zone.run(() => ... /* code here that modifies Angulars model from the outside */);
You can also get the zone outside Angular
bootstrap(AppComponent, ...).then((ref => ref.instance.injector.get(NgZone));
(Not sure if this is 100% correct, I'm just on my phone and looking up is cumbersome. Please post a comment if you can't make it work.

Clean and generic project structure for GO applications and mongodb [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 4 years ago.
Improve this question
I want to build an API based application using GO and MongoDB. I'm from Asp.net MVC background. Probably if I make an architecture with MVC web application things to be consider are
Separation of concerns(SoC)
DataModel
BusinessEntities
BusinessServices
Controllers
Dependeny Injection and Unity of Work
Unit Testing
MoQ or nUnit
Integration with UI frameworks
Angularjs or others
RESTful urls that enables SEO
Below architecture could be a solution for my need in MVC based appications
There are resources around the web to build Asp.Net or Java based applications, but I have not find solution to Golang application architecture.
Yes GO is different to C# or Java, but still there are Structs, Interfaces to create reusable code and a generic application architecture.
Consider above points in mind, how we can make a clean and reusable project structure in GO applications and a generic repositories for DB(Mongodb) transactions. Any web resources also a great point to start.
It depends on your own style and rules, in my company, we develop our projects this way:
Configuration is determined by environment variables, so we have a company/envs/project.sh file which has to be evaluated before service (outside the project in the image).
We add a zscripts folder that contains all extra scripts, like adding users or publishing a post. Intended to be used only for debug proposes.
Data models (entities) are in a package called project/models.
All controllers and views (HTML templates) are categorized into "apps" or "modules". We use the REST path as main group delimiter, so path /dogs goes to package project/apps/dogs and /cats to project/apps/cats.
Managers are in their separated package at project's root project/manager.
Static files (.css, .png, .js, etc.) are located at project/static/[app/]. Sometimes is required to have the optional [app/] folder, but it only happens when two apps have dashboards or conflicting file names. Most of cases you won't need to use [app/] for static resources.
Managers
We call a manager, a package that contains pure functions which helps apps to perform its task, for example, databases, cache, S3 storage, etc. We initialize each manager calling package.Startup() before we start to listen, and finalize calling package.Finalize() when program is interrupted.
An example of a manager could be project/cache/cache.go:
type Config struct {
RedisURL string `envconfig:"redis_url"`
}
var config Config
var client *redis.Client
func Startup(c Config) error {
config = c
client, err := redis.Dial(c.RedisURL)
return err
}
func Set(k,v string) error {
return client.Set(k, v)
}
in main.go (or your_thing_test.go):
var spec cache.Config
envconfig.Process("project", &spec)
cache.Startup(spec)
And in a app (or module):
func SetCacheHandler(_ http.ResponseWriter, _ *http.Request){
cache.Set("this", "rocks")
}
Modules
A module is a container of views and controllers that are isolated from other modules, using our configuration I would recommend to not create dependencies between modules. Modules are also called apps.
Each module configures its routes using a router, sub-router or what your framework provides, for example (file project/apps/dogs/configure.go):
func Configure(e *echo.Echo) {
e.Get("/dogs", List)
}
Then, all handlers live in project/apps/dogs/handlers.go:
// List outputs a dog list of all stored specimen.
func List(c *echo.Context) error {
// Note the use of models.Xyz
var res := make([]models.Dog, 0) // A little trick to not return nil.
err := store.FindAll("dogs", nil, &res) // Call manager to find all dogs.
// handle error ...
return c.JSON(200, res) // Output the dogs.
}
Finally you configure the app in main (or in a test):
e := echo.New()
dogs.Configure(e)
// more apps
e.Run(":8080")
Note: for views, you can add them to project/apps/<name>/views folder and configure them the using the same function.
Other
Sometimes we also add a project/constants and a project/utils package.
Here is what it looks like:
Note that in above sample, templates are separated from apps, thats because its a placeholder, directory is empty.
Hope it was useful. Greetings from México :D.
I've also struggled about how to structure my Go web APIs in the past and don't know any web resources that tell you exactly how to write a Go web API.
What I did was just check out other projects on Github and try out how they structured their code, for example, the Docker repo has very idomatic Go code on it's API.
Also, Beego is a RESTful framework that generates the project structure for you in a MVC way and according to their docs, it can also be used for APIs.
I've been building a web APIs in golang for a little while now.
You'll have to do some research but I can give you some starting points:
Building Web Apps with Go -- ebook
github.com/julienschmidt/httprouter -- for routing addresses
github.com/unrolled/render/ -- for rendering various forms of responses(JSON, HTML, etc..)
github.com/dgrijalva/jwt-go -- JSON Web Tokens
www.gorillatoolkit.org/pkg/sessions -- Session Management
And for reference on how some things work together in the end:
Go Web API Repo -- personal project
1. Separation of concerns (SoC)
I haven't worked with SoC directly, but I have my own pattern. You can adapt to whatever pattern (MVC, your own, etc.).
In my code, I separate my code into different packages:
myprojectname (package main) — Holds the very basic setup and configuration/project consts
* handlers (package handlers) — Holds the code that does the raw HTTP work
* models (package models) — Holds the models
* apis (NOT a package)
- redis (package redis) — Holds the code that wraps a `sync.Pool`
- twilio (package twilio) — Example of layer to deal with external API
Notes:
In each package other than main, I have a Setup() function (with relevant arguments) that is called by the main package.
For the packages under the apis folder, they are often just to initialize external Go libraries. You also can directly import existing libraries into the handlers/models without an apis package.
I setup my mux as an exported global in the handlers package like this...
Router := mux.NewRouter()
...and then create a file for each URL (different methods with the same URL are in the same file). In each file, I use Go's init() function, which is ran after global variables are initialized (so it's safe to use the router) but before main() is ran (so it's safe for main to assume everything has been setup). The great thing about init() is that you can have as many of those methods as you want in a single package, so they automatically get ran when the package is imported.
Main then imports myprojectname/handlers and then serves the handlers.Router in main.
2. Dependency Injection and Unity of Work
I haven't worked with Unity of Work, so I have no idea of possible Go implementations.
For DI, I build an interface that both the real object and the mock objects will implement.
In the package, I add this to the root:
var DatabaseController DatabaseControllerInterface = DefaultController
Then, the first line of each test I can change DatabaseController to whatever that test needs. When not testing, the unit tests should not be ran, and it defaults to DefaultController.
3. Unit Testing
Go provides a built in testing with the go test package command. You can use go test --cover to also emit a coverage percent. You can even have coverage displayed in your browser, highlighting the parts that are/aren't covered.
I use the testify/assert package to help me with testing where the standard library falls short:
// something_test.go
//
// The _test signifies it should only be compiled into a test
// Name the file whatever you want, but if it's testing code
// in a single file, I like to do filename_test.go.
package main
import (
"testing"
"github.com/stretchr/testify/assert"
)
func TestMath(t *testing.T) {
assert.Equal(t, 3+1, 4)
}
4. Integration with UI frameworks
I haven't seen any for Angular. Although I haven't used it, Go has a good template engine built into the standard lib.
5. RESTful URLs that enables SEO
Again, I can't help you here. It's up to you: send proper status codes (don't send a 200 with a 404 page as you'll get docked for duplicate pages), don't duplicate pages (pay attention to google.com/something vs google.com/something/; hopefully your framework will not mess this up), don't try to trick the search engine, and so on.
To my mind Go webapp project folder on production server can looks like on your picture just much simpler. Nothing special in assets structure - Static, Templates, Content, Styles, Img, JSlibs, DBscripts etc. usual folders. Nothing special in WebAPI - as usual you design which URI will respond required functionality and route requests to handlers accordingly. Some specifics - many gophers don't believe in MVC architecture, it's up to you surely. And you deploy one staticaly linked executable without dependencies. In your development environment you structure yours and imported/vendored sorce files in $GOPATH as in stdlib done but deploy only one executable in production environment, sure with static assets needed. You can see how to orginize Go source packages just in stdlib. Having just one executable what would you structure on production?

What is the correct way to add js libraries to mean.io applications?

I am trying to add underscore to my mean.io application. I'm not sure where to link the js library to the page as it doesn't have a main html page like the Angular generator does.
I manually added it via the config/assets.json file and it works however the dev server keeps crashing saying _ is undefined (even though the web app uses the _ function ok and returns the data just before the dev server stops).
I asume I must be doing this wrong.
What is the correct way to add custom js libraries to a mean.io project?
In your package app.js file add
<your package>.aggregateAsset('js', '../<path_to_js_lib in "public/assets" folder>',{
absolute: false
});

node-webkit equivalent for sinatra?

I've been thinking about learning how to make simple Mac OS X applications based on web-technology and I came across node-webkit which seems compelling. However, I've recently invested in learning the basics of Sinatra/Ruby and I wanted to stay on that course.
Is there a "node-webkit equivalent" for developers who use Sinatra? Or, is there a recommended way to use the Sinatra framework (or Ruby) to build OS X apps that are essentially web wrappers?
Sinatra is a server-side framework.
Contrary to Node-webkit which is on client side.
If you need to interact with a server, you can still use sinatra (as well as node.js, php, ...) on your server.
But if you are looking for a framework like sinatra on node.js, you should look into Express.js : https://npmjs.org/package/express
Node-webkit can use file or http, and which to use depends on your needs. The majority of the time you shouldn't need to, Node-webkit runs completely client-side using only HTML, javascript, and css. You certainly can initialize a local webserver when Node-webkit loads, but first try making a basic "Hello World" application to learn how it works.
If you still think you need to spin up a web server, then the code might look something like this (I'm using Express.js):
// Retrieve libraries...
var expressPort = 6014
var NodeWebkit = require('nw.gui');
// Call focus to application...
NodeWebkit.Window.get().focus();
// Instantiate the Express Server...
var spawn = require("child_process").spawn;
spawn("node", ['./server/server', expressPort]);
// Request director page...
window.location.replace('http://localhost:'+expressPort);
In order to use the Node-webkit features from a page on localhost you will also need to add the following line beneath the root of your package.json:
node-remote": "<local>
Note: While this does work, you must really consider whether it makes sense. In other words, is you application fully self-contained? If nothing will access that content except the application then you don't need it.
For my application I am using Node-webkit as an admin console for creating/managing broadcasts. (hence the local webserver)
Nw is not a web framework. Nw does not use a http protocol; it does use a file protocol.
Nw is composed of chromium and nodejs, which allows you to run both DOM and node.js stuff -- without setting up a web server.

Resources