Appunti di studio tutorial MeteorJS (http://www.meteor.com)
Appunti da Simple-todos
Init del progetto
https://www.meteor.com/tutorials/angular/creating-an-app
meteor create simple-todos cd simple-todos meteor npm install meteor
Applicazione pubblicata su : http://localhost:3000
Templates
https://www.meteor.com/tutorials/angular/templates
Rimuovere Blaze (ui di default) a aggiungere il supporto per Angular
meteor remove blaze-html-templates meteor add angular-templates meteor npm install
HTML files in Meteor define templates
Meteor parses all of the regular .HTML files in your app folder and identifies three top-level tags: <head>, <body>, and <template>.
Everything inside any <head> tags is added to the head section of the HTML sent to the client, and everything inside <body> tags is added to the body section, just like in a regular HTML file.The angular-meteor package parses all of the html files in your app folder and puts them in Angular’s template cache with the id of their full path.
So, for example, when a file is named my-angular-template.html is placed in the client folder, it will be available for ng-include or ui-router with the name client/my-angular-template.html.All of the code in your html files is compiled with Angular. Angular binds the data into our templates just like any other Angular app.
Implementazione lato client:
Collections
http://guide.meteor.com/collections.html
Collections are Meteor’s way of storing persistent data (example: local mongodb)
The special thing about collections in Meteor is that they can be accessed from both the server and the client, making it easy to write view logic without having to write a lot of server code.
Security gestita negli steps successivi del tutorial.
They also update themselves automatically, so a view component backed by a collection will automatically display the most up-to-date data.To create the collection, we define a new tasks module that creates a Mongo collection and exports it
Notice that we place this file in a new imports/api directory.
This is a sensible place to store the API of your application—for now the collections that we’ll use, and later the Publications that read from them and the Methods that write to them.
Caricare i tasks dalla collection (mongodb)
Se si effettua l’inserimento manuale di dati via mongodb client:
meteor mongo db.tasks.insert({ text: "Task inserito a mano!", createdAt: new Date() });
sul browser i dati si aggiornano in automatico (binding automatico mongo – server – client)
Form ed eventi
https://www.meteor.com/tutorials/angular/forms-and-events
Aggiunta di un campo inpunt:
– il campo è bindato ad un model
– l’evento submit richiama la funzione del controller
Riscrittura dell’helper tasks, per mostrare i dati ordinati per data:
Update, remove, click e check
https://www.meteor.com/tutorials/angular/update-and-remove
Aggiunta di un tasto delete e di un checkbox, più relativi metodi nel controller:
Here we bind the checked state of a task to a class with ng-class:
<li ng-class=”{‘checked’: task.checked}”>
Nel css la class checked è di colore diverso e barrata
Running on mobile
https://www.meteor.com/tutorials/angular/running-on-mobile
Non supportato su windows, approfondire su linux
Filtering delle collection mediante selector
https://www.meteor.com/tutorials/angular/filtering-collections
Aggiunta di un checkbox bindato alla variabile hideCompleted del controller:
Quindi bisogna:
– aggiungere l’utilizzo di un selector nel task.find, il cui valore deve essere agganciato a hideCompleted
– reagire dinamicamente, ri-stampare l’elenco dei task ad ogni click
To make Meteor understand Angular bindings and the other way around, we use $scope.getReactively function that turns Angular scope variables into Meteor reactive variables.
Funzione aggiuntiva: stampa del numero di task non completi.
Si appende il metodo .count() al find, si aggancia il valore nel template html con la sintassi {{ $ctrl.incompleteCount }}
Aggiunta account utente
https://www.meteor.com/tutorials/angular/adding-user-accounts
Meteor comes with an accounts system and a drop-in login user interface that lets you add multi-user functionality to your app in minutes.
To enable the accounts system and UI, we need to add the relevant packages.
Aggiunta dei pacchetti necessari:
meteor add accounts-password dotansimha:accounts-ui-angular
accounts-password is a package that includes all the logic for password based authentication.
dotansimha:accounts-ui-angular includes the <login-buttons> directive that contains all the HTML and CSS we need for user authentication forms.
Aggiunta della dipendenza in client/main.js e del tag su cui agganciare il login nel template:
Creazione della conf di accounts.ui, import nella logica client:
Ora bisogna integrare la logica utente nell’applicazione:
– aggiunta di owner per ogni task
– stampa “aggiungi tasks” solo se loggati
Insert nel db delle informazioni legate all’owner
Uso della direttiava ng-show per mostrare il form di insert solo se la funzione currentUser ritorna qualcosa.
La funzione currentUser definita nel controller si appoggia alle funzioni di accounting di meteor:
Stampa dell’owner del task a fianco al task stesso:
Struttura mongodb
Meteor mongo va in bind sulla 3001
Security with methods
https://www.meteor.com/tutorials/angular/security-with-methods
A questo punto bisogna impedire al client di richiamare direttamente delle insert/delete/update: andremo a scrivere dei metodi che facciano i controlli necessari (logged in/permission) prima di modificare i dati.
Per prima cosa bisogna disattivare la modalità “insecure” che permette l’accesso diretto ai dati:
meteor remove insecure
Se si rilancia la applicazione, i tasti funzione non faranno più nulla in quanto le loro operazioni sono inibite.
E’ necessario scrivere un metodo per ogni operazione che vogliamo andare a fare sul database, ad esempio nelle API (/imports/api/tasks.js)
I metodi vanno definiti in modo che sia il client che il server li possano usare (vedi oltre, optimistic UI).
Vengono aggiunti check sull contenuto e sulla autenticazione (al momento solo per la insert, da implementare per remove e update):
Quindi nel controller andiamo a richiamare i metodi appena creati, invece delle funzioni di accesso diretto:
Funzione addTask prima :
Modificata in :
Optimistic UI: la app lato client simula l’inserimento dati e pre-aggiorna il client: se la risposta del server è consistente OK, altrimenti il client viene “patchato” e visualizza i dati inviati dal server
http://info.meteor.com/blog/optimistic-ui-with-meteor-latency-compensation
Publish e subscribe
https://www.meteor.com/tutorials/angular/publish-and-subscribe
Altra feature di security da attivare: di default la app di meteor è in autopublish, ovvero tutto il contenuto del mongodb è condiviso con il client.
I meccanismi di publish e subscribe permettono:
– al server di pubblicare determinati contenuti
– al client di registrarsi solo a quelli che servono
Per prima cosa si rimuove l’autopublish:
meteor remove autopublish
Se si rilancia l’app, la task list sarà vuota: il server non pubblica nulla, il client non si registra a nulla.
Per riattivare le funzionalità :
Esempio per publish / subscribe: implementare un tasto “TASK PRIVATO” e fare in modo che il server pubblichi i dati che siano:
– pubblici
– privati solo se l’owner coincide con l’utente loggato
Aggiunta del pulsante “set private”, mostrato solo se l’owner è l’utente loggato al momento:
Dobbiamo quindi creare il metodo per gestire il setPrivate:
e implementare la chiamata al metodo all’interno del controller, agganciato a setPrivate (vedi nel template):
Infine, gestire il publishing in funzione del setprivate:
A questo punto bisogna gestire nei metodi i controli di
– cancellazione (solo se loggato e non private, opzionale: cancellazione solo se owner)
– setChecked (solo se loggato e non private)
TODO: Testing
https://www.meteor.com/tutorials/angular/testing
Struttura filesystem, loading order
http://guide.meteor.com/structure.html
Special directories
By default, any JavaScript files in your Meteor application folder are bundled and loaded on both the client and the server. However, the names of the files and directories inside your project can affect their load order, where they are loaded, and some other characteristics. Here is a list of file and directory names that are treated specially by Meteor:
imports
Any directory named imports/ is not loaded anywhere and files must be imported using import.
node_modules
Any directory named node_modules/ is not loaded anywhere. node.js packages installed into node_modules directories must be imported using import or by using Npm.depends in package.js.
client
Any directory named client/ is not loaded on the server. Similar to wrapping your code in if (Meteor.isClient) { … }.
All files loaded on the client are automatically concatenated and minified when in production mode. In development mode, JavaScript and CSS files are not minified, to make debugging easier.
CSS files are still combined into a single file for consistency between production and development, because changing the CSS file’s URL affects how URLs in it are processed.
HTML files in a Meteor application are treated quite a bit differently from a server-side framework. Meteor scans all the HTML files in your directory for three top-level elements: <head>, <body>, and <template>.
The head and body sections are separately concatenated into a single head and body, which are transmitted to the client on initial page load.
server
Any directory named server/ is not loaded on the client. Similar to wrapping your code in if (Meteor.isServer) { … }, except the client never even receives the code. Any sensitive code that you don’t want served to the client, such as code containing passwords or authentication mechanisms, should be kept in the server/ directory.
Meteor gathers all your JavaScript files, excluding anything under the client, public, and private subdirectories, and loads them into a Node.js server instance. In Meteor, your server code runs in a single thread per request, not in the asynchronous callback style typical of Node.
public
All files inside a top-level directory called public/ are served as-is to the client. When referencing these assets, do not include public/ in the URL, write the URL as if they were all in the top level. For example, reference public/bg.png as <img src=’/bg.png’ />. This is the best place for favicon.ico, robots.txt, and similar files.
private
All files inside a top-level directory called private/ are only accessible from server code and can be loaded via the Assets API. This can be used for private data files and any files that are in your project directory that you don’t want to be accessible from the outside.
client/compatibility
This folder is for compatibility with JavaScript libraries that rely on variables declared with var at the top level being exported as globals. Files in this directory are executed without being wrapped in a new variable scope. These files are executed before other client-side JavaScript files.
It is recommended to use npm for 3rd party JavaScript libraries and use import to control when files are loaded.
tests
Any directory named tests/ is not loaded anywhere. Use this for any test code you want to run using a test runner outside of Meteor’s built-in test tools.
The following directories are also not loaded as part of your app code:
Files/directories whose names start with a dot, like .meteor and .git
packages/: Used for local packages
cordova-build-override/: Used for advanced mobile build customizations
programs: For legacy reasons