{"size": 1242, "ext": "js", "max_stars_repo_path": "router/contact.js", "max_stars_repo_name": "Victor1890/Servidor-Web", "max_stars_repo_stars_event_min_datetime": "2020-10-09T22:57:00.000Z", "max_stars_repo_stars_event_max_datetime": "2020-10-09T22:57:00.000Z", "max_issues_repo_path": "router/contact.js", "max_issues_repo_name": "Victor1890/Servidor-Web", "max_issues_repo_issues_event_min_datetime": null, "max_issues_repo_issues_event_max_datetime": null, "max_forks_repo_path": "router/contact.js", "max_forks_repo_name": "Victor1890/Servidor-Web", "max_forks_repo_forks_event_min_datetime": null, "max_forks_repo_forks_event_max_datetime": null}
{"max_stars_count": 1, "max_issues_count": null, "max_forks_count": null, "avg_line_length": 25.875, "max_line_length": 99, "alphanum_fraction": 0.6296296296}
const {Router} = require('express');
const router = Router();
const admin = require('firebase-admin');

// ruta de las credenciales
const serviceAccount = require('../../tarea5-web-service-firebase-adminsdk-ezelb-eda3b16d27.json');

// añadiendo la ruta y credenciales de la base de datos
admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: 'https://tarea5-web-service.firebaseio.com/'
});

// obteniendo la base de datos
const db = admin.database();

const ref = db.ref('contacts');

// Variable para pasar la respuesta de la base de datos entre el GET y el POST
let contacts =[];

router.get('/', (req, res) => {
    ref.once('value', (snapshot) => {
        const data = snapshot.val();        
        res.json(data);
        contacts = data;
    });
});

router.post('/', (req, res) => {
    const {nombre, apellido, telefono} = req.body;
    const newContact = {
        nombre,
        apellido,
        telefono
    }
    let contactsObject = [];
    if(contacts){
        contactsObject = contacts;
        contactsObject.push(newContact);    
    } else {
        contactsObject.push(newContact);    
    }
    ref.set(contactsObject);
    res.send('received');
})

module.exports = router;