Parse Server local + Ionic2 tutorial
En este video creamos una aplicación móvil con un servidor Parse Server instalado localmente en nuestro ordenador y con Ionic2.
Parse Server
Parse Server es un servidor que funciona sobre la plataforma NodeJS y sobre Express server, y que almacena la información en una base de datos MongoDB. Por defecto, Parse Server nos proporciona muchas funcionalidades que serían costosas de implementar si tuviéramos que desarrollarlas por nosotros mismos. Algunas de las funcionalidades que nos proporciona son gestión de usuarios y roles, notificaciones en tiempo real, subida y gestión de ficheros en el servidor, consultas geolocalizada, notificaciones push, etc. Además, con Parse Server tenemos disponible un panel de administración que nos permite crear nuestras APIs (classes) de forma gráfica muy intuitivamente.
Los pasos para tener nuestro Parse Server funcionando son los siguientes:
1 2 3 |
$ git clone https://github.com/ParsePlatform/parse-server-example.git MyAppServer $ npm install $ npm start |
Al clonar el repositorio tenemos el fichero index.js que es el sevidor en sí. A este fichero vamos a agregarle unas líneas de código para incorporar el dashboard de Parse. Antes, tenemos que instalar el paquete parse-dashboard:
1 |
$ npm install parse-dashboard --save |
Y a continuación editamos nuestro fichero index.js e incorporamos las siguientes líneas de código que he resaltado en amarillo:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 |
// Example express application adding the parse-server module to expose Parse // compatible API routes. var express = require('express'); var ParseServer = require('parse-server').ParseServer; var ParseDashboard = require('parse-dashboard'); var path = require('path'); var allowInsecureHTTP = false; var databaseUri = process.env.DATABASE_URI || process.env.MONGODB_URI; if (!databaseUri) { console.log('DATABASE_URI not specified, falling back to localhost.'); } var api = new ParseServer({ databaseURI: databaseUri || 'mongodb://localhost:27017/dev', cloud: process.env.CLOUD_CODE_MAIN || __dirname + '/cloud/main.js', appId: process.env.APP_ID || 'placeId', masterKey: process.env.MASTER_KEY || 'secret', //Add your master key here. Keep it secret! serverURL: process.env.SERVER_URL || 'http://localhost:1337/api', // Don't forget to change to https if needed liveQuery: { classNames: ["Posts", "Comments"] // List of classes to support for query subscriptions } }); // Client-keys like the javascript key or the .NET key are not necessary with parse-server // If you wish you require them, you can set them as options in the initialization above: // javascriptKey, restAPIKey, dotNetKey, clientKey var dashboard = new ParseDashboard({ "apps": [ { "serverURL": "http://localhost:1337/api", "appId": "placeId", "masterKey": "secret", "appName": "PlaceApp" } ] }, allowInsecureHTTP); var app = express(); // Serve static assets from the /public folder app.use('/public', express.static(path.join(__dirname, '/public'))); // Serve the Parse API on the /parse URL prefix var mountPath = process.env.PARSE_MOUNT || '/api'; app.use(mountPath, api); // make the Parse Dashboard available at /dashboard app.use('/dashboard', dashboard); // Parse Server plays nicely with the rest of your web routes app.get('/', function(req, res) { res.status(200).send('I dream of being a website. Please star the parse-server repo on GitHub!'); }); // There will be a test page available on the /test path of your server url // Remove this before launching your app app.get('/test', function(req, res) { res.sendFile(path.join(__dirname, '/public/test.html')); }); var port = process.env.PORT || 1337; var httpServer = require('http').createServer(app); httpServer.listen(port, function() { console.log('Place Server running on port ' + port + '.'); }); // This will enable the Live Query real-time server ParseServer.createLiveQueryServer(httpServer); |
Una vez tenemos nuestro servidor terminado, podemos acceder al dashboard y empezar a diseñar nuestras clases.
Ionic2
Creamos una aplicación Ionic2, y a continuación creamos un provider que será el encargado de obtener la información de nuestro servidor. El código del provider es el siguiente:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
import { Injectable } from '@angular/core'; import { Http, Headers } from '@angular/http'; import 'rxjs/add/operator/map'; @Injectable() export class PlaceService { url: string = 'http://localhost:1337/api/classes/Place'; headers: Headers = new Headers(); constructor(public http: Http) { this.headers.append('Content-Type', 'application/json'); this.headers.append('X-Parse-Application-Id', 'placeId'); } findAll() { return this.http.get(this.url, {headers: this.headers}).map(response => response.json().results); } } |
En el constructor de nuestra página hacemos una llamada al servicio para recuperar la información del servidor:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import { Component } from '@angular/core'; import { NavController } from 'ionic-angular'; import { PlaceService } from '../../providers/place'; @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { places: any[]; constructor(public navCtrl: NavController, public placeService: PlaceService) { this.placeService.findAll().subscribe(places => this.places = places); } } |
Finalmente, actualizamos nuestra plantilla para que muestre la información que hemos obtenido a partir del provider:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
<ion-header> <ion-navbar> <ion-title>Places</ion-title> </ion-navbar> </ion-header> <ion-content padding> <ion-card *ngFor="let place of places"> <img src="{{place.image_url}}"/> <ion-card-content> <ion-card-title> {{place.title}} </ion-card-title> <p>{{place.description}}</p> </ion-card-content> <ion-row> <ion-col> <button ion-button icon-left clear small> <ion-icon name="calendar"></ion-icon> <div>{{place.createdAt | date}}</div> </button> </ion-col> </ion-row> </ion-card> </ion-content> |
Comentarios recientes