Browse Source

super basic test project

master
Andy Wallace 2 years ago
commit
c94d8def46
  1. BIN
      .DS_Store
  2. 80
      _dev_notes.txt
  3. 19
      database-debug.log
  4. 7
      database.rules.json
  5. 46
      firebase.json
  6. 13
      firestore-debug.log
  7. 1
      functions/.gitignore
  8. 162
      functions/index.js
  9. 4483
      functions/package-lock.json
  10. 23
      functions/package.json
  11. 33
      public/404.html
  12. 115
      public/index.html
  13. 94
      public/test.js
  14. 9
      pubsub-debug.log
  15. 4
      test.json
  16. 2
      ui-debug.log

BIN
.DS_Store

Binary file not shown.

80
_dev_notes.txt

@ -0,0 +1,80 @@
**************
2023-09-12
**************
Adding a new firebase project on the firebase console
https://firebase.google.com/docs/web/setup
Making a new folder on my computer
Running `firebase init`
Enabling:
-Emulators
-Realtime Database
-Functions
-Hosting
When I selected choosing an existing project I got this error:
"Error: Failed to list Firebase projects"
https://stackoverflow.com/questions/57941289/how-do-i-solve-error-failed-to-list-firebase-projects-see-firebase-debug-log
`firebase login --reauth` fixed it
Emulator setup
? Which port do you want to use for the functions emulator? 5001
? Which port do you want to use for the firestore emulator? 8080
? Which port do you want to use for the database emulator? 9000
? Which port do you want to use for the hosting emulator? 5000
? Which port do you want to use for the pubsub emulator? 8085
Firebase initialized!
Following this guide to try and do something with the real time database
https://firebase.google.com/docs/database/web/start
I think my database is named chalice-5f2b0.firebaseio.com
Actually, before I do that, I want to see that I can call a test function
Ran into an issue when I tried to run my test functions in the emulator
functions: package.json indicates an outdated version of firebase-functions. Please upgrade using npm install --save firebase-functions@latest in your functions directory.
Doing what that error says, and then restarting the emulator
-lol the port is taken like usual
OK I fixed that but now I can't see my console logs in the logs
Got a barebones version of the skirmish society app going and not giving me CORS errors
Going to try and do anything with the relative database now
I think maybe the instructions I linked to above are for the client site. I want to edit the database from cloud functions. Trying this: https://firebase.google.com/docs/database/extend-with-functions?gen=2nd
The normal docs are not helping you. I think for your cloud function stuff you actually need the admin docs since that is the tool you are using to access the DB
https://firebase.google.com/docs/reference/admin/node/firebase-admin.database.database.md#database_interface
-although I'm still getting stuck here
**************
2023-09-13
**************
OK lets see if I can get the frontend to read the real time database
I'd love to not have to use node for this. But all of google's docs are for node
Taking a look at this
https://rajatamil.medium.com/learn-to-build-firebase-crud-app-with-javascript-part-1-reading-data-b3f8f8e0d924
Github:
https://github.com/softauthor/Firebase/tree/master
Mixed results there
Trying this one
https://dev.to/maasak/set-up-firebase-realtime-database-for-javascript-app-4k0l
The code snippet to write worked like a charm.
Oh shit, no the other things you set also work. You just had to set the DB to readable

19
database-debug.log

@ -0,0 +1,19 @@
WARNING: An illegal reflective access operation has occurred
WARNING: Illegal reflective access by io.netty.util.internal.ReflectionUtil (file:/Users/andrewwallace/.cache/firebase/emulators/firebase-database-emulator-v4.11.0.jar) to field sun.nio.ch.SelectorImpl.selectedKeys
WARNING: Please consider reporting this to the maintainers of io.netty.util.internal.ReflectionUtil
WARNING: Use --illegal-access=warn to enable warnings of further illegal reflective access operations
WARNING: All illegal access operations will be denied in a future release
15:22:22.324 [NamespaceSystem-akka.actor.default-dispatcher-4] INFO akka.event.slf4j.Slf4jLogger - Slf4jLogger started
15:22:22.518 [main] INFO com.firebase.server.forge.App$ - Listening at 127.0.0.1:9000
15:22:26.435 [NamespaceSystem-akka.actor.default-dispatcher-5] INFO com.firebase.core.namespace.NamespaceActor - chalice-5f2b0-default-rtdb successfully activated FBKV (SurveyIdle(0)) wait: 146ms, init: 0ms
15:22:27.046 [NamespaceSystem-blocking-namespace-operation-dispatcher-7] INFO com.firebase.core.namespace.StateManager - Namespace chalice-5f2b0-default-rtdb status Active to Active
15:22:35.766 [FirebaseWorkerPool-1-2] WARN com.firebase.core.persistence.backend.dummy.EmulatorMetadataPersistence - Multiple projectIds are not recommended in single project mode. Requested
namespace chalice-5f2b0, but the emulator is configured for chalice-5f2b0-default-rtdb. To
opt-out of single project mode add/set the single_project_mode: false property in
the firebase.json emulators config.
15:22:35.772 [NamespaceSystem-akka.actor.default-dispatcher-4] INFO com.firebase.core.namespace.NamespaceActor - chalice-5f2b0 successfully activated FBKV (SurveyIdle(0)) wait: 4ms, init: 0ms
15:23:03.576 [Thread-0] INFO com.firebase.server.forge.App$ - Attempting graceful shutdown.
15:23:03.580 [NamespaceSystem-akka.actor.default-dispatcher-9] INFO com.firebase.core.namespace.Terminator$Terminator - 2 actors left to terminate: chalice-5f2b0, chalice-5f2b0-default-rtdb
15:23:03.583 [NamespaceSystem-akka.actor.default-dispatcher-6] INFO com.firebase.core.namespace.NamespaceActor - stopped namespace actor for chalice-5f2b0-default-rtdb
15:23:03.583 [NamespaceSystem-akka.actor.default-dispatcher-5] INFO com.firebase.core.namespace.NamespaceActor - stopped namespace actor for chalice-5f2b0
15:23:03.586 [Thread-0] INFO com.firebase.server.forge.App$ - Graceful shutdown complete.

7
database.rules.json

@ -0,0 +1,7 @@
{
/* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
"rules": {
".read": true,
".write": true
}
}

46
firebase.json

@ -0,0 +1,46 @@
{
"functions": [
{
"source": "functions",
"codebase": "default",
"ignore": [
"node_modules",
".git",
"firebase-debug.log",
"firebase-debug.*.log"
]
}
],
"database": {
"rules": "database.rules.json"
},
"hosting": {
"public": "public",
"ignore": [
"firebase.json",
"**/.*",
"**/node_modules/**"
]
},
"emulators": {
"functions": {
"port": 5001
},
"firestore": {
"port": 8080
},
"database": {
"port": 9000
},
"hosting": {
"port": 5000
},
"pubsub": {
"port": 8085
},
"ui": {
"enabled": true
},
"singleProjectMode": true
}
}

13
firestore-debug.log

@ -0,0 +1,13 @@
Sep 13, 2023 3:22:20 PM com.google.cloud.datastore.emulator.firestore.websocket.WebSocketServer start
INFO: Started WebSocket server on ws://127.0.0.1:9150
API endpoint: http://127.0.0.1:8080
If you are using a library that supports the FIRESTORE_EMULATOR_HOST environment variable, run:
export FIRESTORE_EMULATOR_HOST=127.0.0.1:8080
Dev App Server is now running.
Sep 13, 2023 3:22:35 PM com.google.cloud.datastore.emulator.firestore.websocket.WebSocketChannelHandler initChannel
INFO: Connected to new websocket client
*** shutting down gRPC server since JVM is shutting down
*** server shut down

1
functions/.gitignore

@ -0,0 +1 @@
node_modules/

162
functions/index.js

@ -0,0 +1,162 @@
//Function stuff
const functions = require("firebase-functions");
const cors = require('cors');
const express = require('express');
const app = express();
var allowedOrigins = ['http://localhost:8000',
'http://localhost:5000',
'http://127.0.0.1:5000',
'http://localhost:3000'
];
app.use(cors({
origin: allowedOrigins
}));
/*
// I THINK THIS IS JUST FOR THE CLIENT SIDE
//Real Time Database
//https://firebase.google.com/docs/database/web/start (slightly modified)
const initializeApp = require("firebase/app");
const getDatabase = require("firebase/database");
const firebaseConfig = {
databaseURL: "https://chalice-5f2b0.firebaseio.com",
};
// Initialize Firebase
const firebase = initializeApp(firebaseConfig);
// Initialize Realtime Database and get a reference to the service
const database = getDatabase(firebase);
*/
//Real Time Database
// The Cloud Functions for Firebase SDK to setup triggers and logging.
const {onRequest} = require("firebase-functions/v2/https");
const {onValueCreated} = require("firebase-functions/v2/database");
const {logger} = require("firebase-functions");
// The Firebase Admin SDK to access the Firebase Realtime Database.
const admin = require("firebase-admin");
admin.initializeApp();
// // Create and deploy your first functions
// // https://firebase.google.com/docs/functions/get-started
//
// exports.helloWorld = functions.https.onRequest((request, response) => {
// console.log("hello hello hello")
// functions.logger.info("Hello logs!", {structuredData: true});
// //response.send("Hello from Firebase!");
// response.json( {response: "Hi there from hellow world" } );
// });
app.post('/testo', async(req, res) => {
console.log("I got a hit at testo");
res.json( {response: "I am a test" } );
})
function setup(){
console.log("This is a setup function");
}
setup();
exports.app = functions.https.onRequest(app);
console.log("bottom of test functions");
//testing realtime database functions
//https://github.com/firebase/functions-samples/blob/3313875c66090c1e8f9e4cb202dd4daa096f18d1/Node/quickstarts/uppercase-rtdb/functions/index.js#L20-L27
// [START addmessage]
// Take the text parameter passed to this HTTP endpoint and insert it into the
// Realtime Database under the path /messages/:pushId/original
// [START addMessageTrigger]
exports.addmessage = onRequest(async (req, resp) => {
// [END addMessageTrigger]
// Grab the text parameter.
const original = req.query.text;
// [START adminSdkPush]
// Push the new message into the Realtime Database
// using the Firebase Admin SDK.
const snapshot = await admin
.database()
.ref("/messages")
.push({original: original});
// Redirect with 303 SEE OTHER to the URL
// of the pushed object in the Firebase console.
resp.redirect(303, snapshot.ref.toString());
// [END adminSdkPush]
});
// [END addmessage]
app.post('/add_message', async(req, res) => {
console.log("I got a hit at add message");
let this_text = req.body.text;
if (!this_text){
this_text = "test message";
}
console.log("TRYING TO WRITE "+this_text);
// const snapshot = await admin
// .database()
// .ref("/tests/umbo")
// .push({text: "buppo"});
const snapshot = await admin
.database()
.ref("/messages/")
.child("testo")
.set({"text": this_text});
// const snapshot2 = await admin
// .database()
// .ref("/messages")
// console.log(snapshot2);
//this does not work
// const db = await admin.database();
// const snapshot = db.set(db.ref("/tests/hubbo"), {text: "yappy"});
res.json( {response: "I tried to write it!" } );
})
app.post('/read_testo', async(req, res) => {
var ref = await admin.database().ref('messages/testo');
let my_data;
await ref.on("value", function(snapshot) {
snapshot.forEach(function(data) {
console.log("Key " + data.key + " has value: " + data.val());
my_data = data;
res.json( {response: my_data } );
});
})
})
//This works to capture any new messages and then add a field for uppercase.
//Could easily use this to add time stamps
/*
exports.makeuppercase = onValueCreated(
"/messages/{pushId}/text",
(event) => {
console.log("firing the upper caser");
// Grab the current value of what was written to the Realtime Database.
const original = event.data.val();
logger.log("Uppercasing", event.params.pushId, original);
const uppercase = original.toUpperCase();
// You must return a Promise when performing
// asynchronous tasks inside a function, such as
// writing to the Firebase Realtime Database.
// Setting an "uppercase" sibling in the
// Realtime Database returns a Promise.
return event.data.ref.parent.child("uppercase").set(uppercase);
},
);
*/

4483
functions/package-lock.json

File diff suppressed because it is too large

23
functions/package.json

@ -0,0 +1,23 @@
{
"name": "functions",
"description": "Cloud Functions for Firebase",
"scripts": {
"serve": "firebase emulators:start --only functions",
"shell": "firebase functions:shell",
"start": "npm run shell",
"deploy": "firebase deploy --only functions",
"logs": "firebase functions:log"
},
"engines": {
"node": "16"
},
"main": "index.js",
"dependencies": {
"firebase-admin": "^10.0.2",
"firebase-functions": "^4.4.1"
},
"devDependencies": {
"firebase-functions-test": "^0.2.0"
},
"private": true
}

33
public/404.html

@ -0,0 +1,33 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Page Not Found</title>
<style media="screen">
body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
#message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px 16px; border-radius: 3px; }
#message h3 { color: #888; font-weight: normal; font-size: 16px; margin: 16px 0 12px; }
#message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
#message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
#message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
#message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
#message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
#load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
@media (max-width: 600px) {
body, #message { margin-top: 0; background: white; box-shadow: none; }
body { border-top: 16px solid #ffa100; }
}
</style>
</head>
<body>
<div id="message">
<h2>404</h2>
<h1>Page Not Found</h1>
<p>The specified file was not found on this website. Please check the URL for mistakes and try again.</p>
<h3>Why am I seeing this?</h3>
<p>This page was generated by the Firebase Command-Line Interface. To modify it, edit the <code>404.html</code> file in your project's configured <code>public</code> directory.</p>
</div>
</body>
</html>

115
public/index.html

@ -0,0 +1,115 @@
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Welcome to Firebase Hosting</title>
<!-- generated by firebase when I selected :add firbease to your web app-->
<script type="module">
// Import the functions you need from the SDKs you need
import { initializeApp } from "https://www.gstatic.com/firebasejs/10.3.1/firebase-app.js";
// TODO: Add SDKs for Firebase products that you want to use
// https://firebase.google.com/docs/web/setup#available-libraries
// Your web app's Firebase configuration
const firebaseConfig = {
apiKey: "AIzaSyAIsg3tOBb1oKgwKLQNNvjE7JvcFpflVc8",
authDomain: "chalice-5f2b0.firebaseapp.com",
databaseURL: "https://chalice-5f2b0-default-rtdb.firebaseio.com",
projectId: "chalice-5f2b0",
storageBucket: "chalice-5f2b0.appspot.com",
messagingSenderId: "1063836259576",
appId: "1:1063836259576:web:56b4e28411ee3f39aa570d"
};
// Initialize Firebase
const app = initializeApp(firebaseConfig);
</script>
<!-- update the version number as needed -->
<script defer src="/__/firebase/10.3.1/firebase-app-compat.js"></script>
<!-- include only the Firebase features as you need -->
<script defer src="/__/firebase/10.3.1/firebase-auth-compat.js"></script>
<script defer src="/__/firebase/10.3.1/firebase-database-compat.js"></script>
<script defer src="/__/firebase/10.3.1/firebase-firestore-compat.js"></script>
<script defer src="/__/firebase/10.3.1/firebase-functions-compat.js"></script>
<script defer src="/__/firebase/10.3.1/firebase-messaging-compat.js"></script>
<script defer src="/__/firebase/10.3.1/firebase-storage-compat.js"></script>
<script defer src="/__/firebase/10.3.1/firebase-analytics-compat.js"></script>
<script defer src="/__/firebase/10.3.1/firebase-remote-config-compat.js"></script>
<script defer src="/__/firebase/10.3.1/firebase-performance-compat.js"></script>
<!--
initialize the SDK after all desired features are loaded, set useEmulator to false
to avoid connecting the SDK to running emulators.
-->
<script defer src="/__/firebase/init.js?useEmulator=true"></script>
<!-- Andy stuff -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
<script src="test.js" defer></script>
<style media="screen">
body { background: #ECEFF1; color: rgba(0,0,0,0.87); font-family: Roboto, Helvetica, Arial, sans-serif; margin: 0; padding: 0; }
#message { background: white; max-width: 360px; margin: 100px auto 16px; padding: 32px 24px; border-radius: 3px; }
#message h2 { color: #ffa100; font-weight: bold; font-size: 16px; margin: 0 0 8px; }
#message h1 { font-size: 22px; font-weight: 300; color: rgba(0,0,0,0.6); margin: 0 0 16px;}
#message p { line-height: 140%; margin: 16px 0 24px; font-size: 14px; }
#message a { display: block; text-align: center; background: #039be5; text-transform: uppercase; text-decoration: none; color: white; padding: 16px; border-radius: 4px; }
#message, #message a { box-shadow: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24); }
#load { color: rgba(0,0,0,0.4); text-align: center; font-size: 13px; }
@media (max-width: 600px) {
body, #message { margin-top: 0; background: white; box-shadow: none; }
body { border-top: 16px solid #ffa100; }
}
</style>
</head>
<body>
<div id="message">
<h2>Welcome</h2>
<h1>Firebase Hosting Setup Complete</h1>
<p>You're seeing this because you've successfully setup Firebase Hosting. Now it's time to go build something extraordinary!</p>
<a target="_blank" href="https://firebase.google.com/docs/hosting/">Open Hosting Documentation</a>
</div>
<p id="load">Firebase SDK Loading&hellip;</p>
<script>
document.addEventListener('DOMContentLoaded', function() {
const loadEl = document.querySelector('#load');
// // 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥
// // The Firebase SDK is initialized and available here!
//
// firebase.auth().onAuthStateChanged(user => { });
// firebase.database().ref('/path/to/ref').on('value', snapshot => { });
// firebase.firestore().doc('/foo/bar').get().then(() => { });
// firebase.functions().httpsCallable('yourFunction')().then(() => { });
// firebase.messaging().requestPermission().then(() => { });
// firebase.storage().ref('/path/to/ref').getDownloadURL().then(() => { });
// firebase.analytics(); // call to activate
// firebase.analytics().logEvent('tutorial_completed');
// firebase.performance(); // call to activate
//
// // 🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥🔥
try {
let app = firebase.app();
let features = [
'auth',
'database',
'firestore',
'functions',
'messaging',
'storage',
'analytics',
'remoteConfig',
'performance',
].filter(feature => typeof app[feature] === 'function');
loadEl.textContent = `Firebase SDK loaded with ${features.join(', ')}`;
} catch (e) {
console.error(e);
loadEl.textContent = 'Error loading the Firebase SDK, check the console.';
}
});
</script>
</body>
</html>

94
public/test.js

@ -0,0 +1,94 @@
let endpoint = "http://127.0.0.1:5001/chalice-5f2b0/us-central1/app/"
function begin(){
console.log( "I have begin" );
}
begin();
// Initialize Firebase
//uhhhh maybe this already happens in that module
//https://rajatamil.medium.com/learn-to-build-firebase-crud-app-with-javascript-part-1-reading-data-b3f8f8e0d924
// const config = {
// apiKey: "AIzaSyAIsg3tOBb1oKgwKLQNNvjE7JvcFpflVc8",
// authDomain: "chalice-5f2b0.firebaseapp.com",
// databaseURL: "https://chalice-5f2b0-default-rtdb.firebaseio.com",
// projectId: "chalice-5f2b0",
// storageBucket: "chalice-5f2b0.appspot.com",
// messagingSenderId: "1063836259576",
// appId: "1:1063836259576:web:56b4e28411ee3f39aa570d"
// };
// firebase.initializeApp(config);
const dbRef = firebase.database().ref();
const usersRef = dbRef.child(`users`);
function write_test(_text){
console.log(_text);
$.post(
endpoint+"add_message",
{text:_text},
function (response) {
console.log("I got:")
console.log(response)
}
)
}
function read_test(){
console.log( "reading" );
$.post(
endpoint+"read_testo",
{},
function (response) {
console.log("I read:")
console.log(response)
}
)
}
$( document ).ready(async function() {
console.log( "page loaded" );
console.log(usersRef)
//this works to write to the DB (which I do not really need to do)
firebase.database().ref('issues/').set({
desc: "yabbo gabbo",
id: "munch of crunk"
});
//this fires as soon as page is loaded
//this listed out all key values any time any one of them is changed
await usersRef.on("value", function(snapshot) {
console.log("I am looking at values");
snapshot.forEach(function(data) {
console.log("Key " + data.key + " has value: " + data.val());
});
})
//this fires when something gets changed, and only the changed value gets listed
await usersRef.on("child_changed", function(snapshot) {
console.log("I am changing of values");
snapshot.forEach(function(data) {
console.log("Key " + data.key + " now has value: " + data.val());
});
})
//this fires as soon as the page is loaded
await usersRef.on("child_added", snap => {
let user = snap.val();
console.log("child added: "+user.name)
// let $li = document.createElement("li");
// $li.innerHTML = user.name;
// $li.setAttribute("child-key", snap.key);
// $li.addEventListener("click", userClicked)
// userListUI.append($li);
});
});

9
pubsub-debug.log

@ -0,0 +1,9 @@
This is the Google Pub/Sub fake.
Implementation may be incomplete or differ from the real system.
Sep 13, 2023 3:22:22 PM com.google.cloud.pubsub.testing.v1.Main main
INFO: IAM integration is disabled. IAM policy methods and ACL checks are not supported
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Sep 13, 2023 3:22:23 PM com.google.cloud.pubsub.testing.v1.Main main
INFO: Server started, listening on 8085

4
test.json

@ -0,0 +1,4 @@
{
"name" : "hello",
"value" : "dog"
}

2
ui-debug.log

@ -0,0 +1,2 @@
Web / API server started at 127.0.0.1:4000
Web / API server started at ::1:4000
Loading…
Cancel
Save