diff --git a/functions/src/index.ts b/functions/src/index.ts index c342527..fd27ca4 100644 --- a/functions/src/index.ts +++ b/functions/src/index.ts @@ -1,11 +1,9 @@ -import * as admin from 'firebase-admin'; import * as functions from 'firebase-functions'; -const pg = require('pg'); import * as uuidv4 from 'uuid/v4'; import * as https from 'https'; -import { createStudy, createUser, Study, User } from '../../src/datastore'; +import { Study, User } from '../../src/datastore'; async function saveUserToSqlApi(apiHost: string, userRecord: { email: string, displayName: string }) { @@ -48,11 +46,53 @@ async function saveUserToSqlApi(apiHost: string, userRecord: { email: string, di // https://firebase.google.com/docs/functions/typescript export const newlyAuthenticatedUser = functions.auth.user().onCreate((user) => saveUserToSqlApi(functions.config().pg.url, user)); +async function saveStudyToSqlApi(apiHost: string, study: Study) { + const options = { + host: apiHost, + path: "/saveNewStudy", + method: "POST", + headers: { + "Content-Type": "application/json" + } + }; + const req = https.request(options, (res) => { + const logObject = { + url: res.url, + status_code: res.statusCode, + method: res.method, + headers: res.headers + }; + console.log(JSON.stringify(logObject)); + + res.on('data', (d) => { + process.stdout.write(d); + }); + + }); + req.on('error', (e) => { + console.error('catch error: ', e); + }); + + console.log('sending payload: ', JSON.stringify({ + ...study + })); + req.write(JSON.stringify(study)); + req.end(); + +} + export const newStudyCreated = functions.firestore.document('/study/{studyId}').onCreate((snapshot: FirebaseFirestore.DocumentSnapshot, ctx: functions.EventContext) => { const newStudy = snapshot.data() as Study; - // createStudy(pool, newStudy, ['gender', 'location']).then(res => { - // console.log(`successfully added study: ${newStudy} to sql database`); - // }).catch(err => { - // console.error(err) - // }); + saveStudyToSqlApi(functions.config().pg.url, { + studyId: uuidv4(), + userId: 'f1f8fdb1-dbdc-4f44-99d3-44695df74fee', + ...newStudy + }).then(result => { + console.log('saved new study to gcp: ', result); + }).catch(err => console.error(err)); }); + +const myStudy = { + title: 'my title', + protocolVersion: '1.0' +} diff --git a/index.html b/index.html index 36a8eeb..f016d0c 100644 --- a/index.html +++ b/index.html @@ -12,8 +12,8 @@
-
-
+
- - + diff --git a/index.js b/index.js index 759f67a..b1c1a11 100644 --- a/index.js +++ b/index.js @@ -14,11 +14,13 @@ const firestore = firebase.firestore(); const auth = firebase.auth(); const ui = new firebaseui.auth.AuthUI(auth); +let myUserId; ui.start('#firebaseui-auth-container', { callbacks: { signInSuccessWithAuthResult: (authResult) => { console.log('sign in is a succes: ', authResult); + document.getElementById('new-study').hidden = false; } }, signInOptions: [ @@ -30,29 +32,37 @@ ui.start('#firebaseui-auth-container', { auth.onAuthStateChanged(function(user) { if (user) { + userId = user.uid; console.log('user: ', user); } }); -const ThorneCliffParkStudy = { - -} - -function saveStudy(db, study) { - db.collection('study').add({ - ...study +function saveStudy(study) { + firestore.collection('study').add({ + ...study }).then(function(docRef) { study_id = docRef.id; console.log("Document written with ID: ", docRef.id); - }) - .catch(function(error) { - console.error("Error adding document: ", error); - }); - + }).catch(function(error) { + console.error("Error adding document: ", error); + }); } function saveUser(db, user) { db.collection('user').add({ - ...user + ...user }) } + + +window.addEventListener("load", function () { + document.getElementById("new-study-form").addEventListener('submit', function (event) { + event.preventDefault(); + const newStudy = { + title: document.getElementById('study-title').value, + protocolVersion: document.getElementById('protocol-version-selection').value + }; + console.log(JSON.stringify(newStudy)); + saveStudy(newStudy); + }); +}); diff --git a/package.json b/package.json index aa51ad0..e2fae3d 100644 --- a/package.json +++ b/package.json @@ -10,7 +10,7 @@ "build-gcp": "cat config/cloud.env | sed 's/=/: /' > .env.yml", "build-scripts": "tsc -m commonJS --rootDir src --outDir js_scripts", "clean": "rm -rf dist/", - "deploy-gcp": "npm run build-gcp && npm run build && cp package.json dist/ && gcloud beta functions deploy saveNewUser --env-vars-file .env.yml --trigger-http --runtime nodejs8 --source dist/", + "deploy-gcp": "npm run build-gcp && npm run build && cp package.json dist/ && gcloud beta functions deploy saveNewStudy --env-vars-file .env.yml --trigger-http --runtime nodejs8 --source dist/", "lint": "tsc --noEmit" }, "devDependencies": { diff --git a/src/datastore.ts b/src/datastore.ts index 371a798..0d3c956 100644 --- a/src/datastore.ts +++ b/src/datastore.ts @@ -94,7 +94,7 @@ function createNewTableFromGehlFields(study: Study, fields: GehlFields[]) { // in other words the study already has the userId references, where should the idea of the study belonging to a user live? in the relationship model it's with a reference id export async function createStudy(pool: pg.Pool, study: Study, fields: GehlFields[]) { const newStudyMetadataQuery = `INSERT INTO data_collection.study (study_id, title, user_id, protocol_version) - VALUES ('${study.studyId}', '${study.title}', '${study.userId}', '1.0')`; + VALUES ('${study.studyId}', '${study.title}', '${study.userId}', ${study.protocolVersion})`; const studyResult = await pool.query(newStudyMetadataQuery); console.log('study result: ', studyResult); const newStudyDataTableQuery = createNewTableFromGehlFields(study, fields); diff --git a/src/sql_database.ts b/src/sql_database.ts deleted file mode 100644 index 956fc40..0000000 --- a/src/sql_database.ts +++ /dev/null @@ -1,25 +0,0 @@ -import "babel-polyfill"; - -import { Request, Response } from 'express'; -import * as pg from 'pg'; -import * as uuid from 'uuid'; - -import { createUser, User } from './datastore'; - -const pgConnectionInfo = { - connectionLimit: 1, - host: process.env.db_host, - user: process.env.db_user, - password: process.env.db_pass, - database: process.env.db_name -} - -const pool = new pg.Pool(pgConnectionInfo); - -// Return a newly generated UUID in the HTTP response. -export async function saveNewUser(req: Request, res: Response) { - const { userId, email, name } = req.body; - const insertQuery = `INSERT INTO users (user_id, email, name) VALUES ('${userId}', '${email}', '${name}')` - const resultFromSave = await createUser(pool, { userId, email, name }); - res.send(req.body); -}; diff --git a/webpack.config.js b/webpack.config.js index 57a7a00..d071d71 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -3,7 +3,7 @@ const webpack = require('webpack'); module.exports = { entry: { - sql_database: ['babel-polyfill', path.resolve(__dirname, 'src/sql_database.ts')] + gcp: ['babel-polyfill', path.resolve(__dirname, 'src/gcp.ts')] }, output: { libraryTarget: 'umd',