Skip to content
This repository has been archived by the owner on Apr 14, 2023. It is now read-only.

Commit

Permalink
add new study
Browse files Browse the repository at this point in the history
  • Loading branch information
Eric Sebastian committed Aug 17, 2018
1 parent 5b0368e commit dcdc5d2
Show file tree
Hide file tree
Showing 7 changed files with 77 additions and 63 deletions.
56 changes: 48 additions & 8 deletions functions/src/index.ts
Original file line number Diff line number Diff line change
@@ -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 }) {
Expand Down Expand Up @@ -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'
}
17 changes: 3 additions & 14 deletions index.html
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@
</head>
<body>
<div id="firebaseui-auth-container"></div>
<div id="new study" class="Container">
<form id="new-study-form">
<div id="new-study" class="Container" hidden>
<form id="new-study-form"">
<label for="study-title">Study Title</label>
<input id="study-title" type="text" name="text">
</br>
Expand All @@ -33,16 +33,5 @@
</form>
</div>
</body>
<script src="index.js"><script/>
<script>
function createNewStudy(event) {
event.preventDefault();
const newStudy = {
title: document.getElementById("study-title").value,
protocol_version: document.getElementById("protocol-version-selection").value
}
}
document.getElementById("new-study-form").addEventListener('submit', createNewStudy);
</script>

<script src="index.js"></script/>
</html>
36 changes: 23 additions & 13 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -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: [
Expand All @@ -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);
});
});
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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": {
Expand Down
2 changes: 1 addition & 1 deletion src/datastore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
25 changes: 0 additions & 25 deletions src/sql_database.ts

This file was deleted.

2 changes: 1 addition & 1 deletion webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -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',
Expand Down

0 comments on commit dcdc5d2

Please sign in to comment.