How can I navigate children in Firebase? - javascript

I am using Firebase Realtime Database. I have some keys in the root. And I have keys and children within these keys. I need to listen to the values of a specific child. For example, the structure is like this:
root
├── d775810
│ ├── datas_for_type
│ │ └── timestamp
│ │ └── multiple list datas
│ └── reportFlag
│ └── timestamp
│ └── flagAnnotation:True
└── a413ba21
├── datas_for_type
│ └── timestamp
│ └── multiple list datas
└── reportFlag
└── timestamp
└── flagAnnotation:False
I need to listen to the "flagAnnotation" child. If it is true, I will access the data with the same timestamp and create a PDF. How can I listen to the values of this child?
I tried this:
dbRef.ref().on("child_added", (snapshot) => {
console.log(`Child added: ${snapshot.key}`);
});
This give only d775810,a413ba21.. and if ı add root, ıt will give them.

Firebase Realtime Database reads always return full nodes. This means that you can't listen for just the flagAnnotation properties.
You can listen for the entire JSON branch however, and then navigate the data snapshot you get to just show the flagAnnotation values.
firebase.database().ref().get('value').then((rootSnapshot) => {
rootSnapshot.forEach((childSnapshot) => {
console.log(childSnapshot.val().reportFlag.timestamp.flagAnnotation);
});
})
If the timestamp in your JSON is dynamic, you'll need another forEach to loop over those children, and it'd become:
firebase.database().ref().get('value').then((rootSnapshot) => {
rootSnapshot.forEach((childSnapshot) => {
const reportFlagSnapshot = childSnapshot.child('reportFlag');
reportFlagSnapshot.forEach((timestampSnapshot) => {
console.log(timestampSnapshot.key, timestampSnapshot.val().flagAnnotation);
})
});
})

Related

Sphinx-js can't find class documentation

I'm trying to setup sphinx_js but I keep receiving this error:
~/test_sphinx_js$ sphinx-build -b html docs/source/ docs/build/html/
Running Sphinx v4.4.0
building [mo]: targets for 0 po files that are out of date
building [html]: targets for 1 source files that are out of date
updating environment: [new config] 1 added, 0 changed, 0 removed
reading sources... [100%] index
Sphinx error:
No documentation was found for object "SomeClass" or any path ending with that.
this is my test project structure:
.
├── docs
│ ├── build
│ │ └── html
│ ├── make.bat
│ ├── Makefile
│ └── source
│ ├── conf.py
│ ├── index.rst
│ ├── _static
│ └── _templates
└── src
└── SomeClass.js
and these are the relevant settings and code:
conf.py
[...]
extensions = ['sphinx_js']
js_source_path = '../../src'
primary_domain = 'js'
[...]
index.rst:
Welcome to SomeDocs's documentation!
====================================
.. toctree::
:maxdepth: 2
:caption: Contents:
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
.. js:autoclass:: SomeClass
SomeClass.js:
/** Class representing something. */
export default class SomeClass {
/**
* Create class.
* #param {string} name - The name of the object.
* #param {string} type - The type of object.
*/
constructor(name, type) {
this.name = name;
this.type = type;
}
}
I must be missing something obvious but I can't wrap my head around it

Rollup & React- How to separate component bundles?

I currently am trying to build a UI Library for React and I am having a little bit of trouble. Currently I am using typescript and rollup, and I am able to bundle a single index.js and I am able to import those components but it is importing the whole library.
Currently:
File structure:
src
--components
-----button
-------button.tsx
-------button.types.ts
-----input
-------input.tsx
-------input.types.ts
-----index.ts
rollup.js
My rollup targets index.ts which has everything exported like so:
export { default as Button} from './button/button'
export { default as Input } from './input/input'
And I am able to import in a react project like so:
import { Button, Input } from 'my-library'
What I would Like to do
I would like that each component is bundled separately and they would be imported like so
import { Input } from 'my-library/input'
import { Button } from 'my-library/button'
What I've Tried:
After reading the docs, it seemed that the preserveModule: true is what I was looking for but then I tried importing as above but it started to complain that nothing was found.
My current rollup.js looks like this:
export default {
input: 'src/index.ts',
output: [
{
exports: 'named',
dir: 'build/',
format: 'esm',
sourcemap: true,
preserveModules: true,
},
],
plugins: [
cleaner({ targets: ['./build'] }),
peerDepsExternal(),
resolve(),
commonjs(),
terser(),
typescript({
exclude: ['**/*.stories.tsx', '**/*.test.tsx'],
}),
],
};
EDIT: I've posted a more comprehensive tutorial on medium here
I tried using preserveModules but it doesnt generate an index.js file for each Components such that I can import like so :
import Button from 'lib/Button'
Hence I came up with a work around to make rollup loop through my src folders to generate a folder with entrypoint for every Component folder i had in src at rootDir
Maintain a strict folder structure with entry point for every Component folder. Do not have loose files, other than index.ts in src folder that have no folders. Name your folders properly like how you want users to import it
src folder structure:
rollup.config.js
src
├── Accordion
│ ├── Accordion.tsx
│ ├── AccordionBody.tsx
│ ├── AccordionButton.tsx
│ ├── AccordionCollapse.tsx
│ ├── AccordionContext.ts
│ ├── AccordionHeader.tsx
│ ├── AccordionItem.tsx
│ ├── AccordionItemContext.ts
│ └── index.ts
├── Alert
│ ├── Alert.tsx
│ └── index.ts
├── Badge
│ ├── Badge.tsx
│ └── index.ts
├── Breadcrumb
│ ├── Breadcrumb.tsx
│ ├── BreadcrumbItem.tsx
│ └── index.ts
├── Button
│ ├── Button.tsx
│ └── index.ts
├── ButtonGroup
│ ├── ButtonGroup.tsx
│ └── index.ts
...
├── Tooltip
│ ├── Tooltip.tsx
│ ├── TooltipBox.tsx
│ └── index.ts
├── index.ts
Its crucial for this case to maintain an entry point for each Component folder. I still maintained an entry point for src folder so that users can still import multiple components from the library with one line
i.e. import {Button, Accordion, ...} from 'lib'
Rollup config
getFolders returns an array of Folder names that are meant for export
loop through getFolders to generate the rollup obj per folder.
For typescript projects, rollup outputs the typings file with preserved folder structure already, so I realised that the folders Accordion, Button etc. were already there with typings file only. Now we need to add the index.js file to it!
import peerDepsExternal from 'rollup-plugin-peer-deps-external';
import resolve from '#rollup/plugin-node-resolve';
import commonjs from '#rollup/plugin-commonjs';
import typescript from 'rollup-plugin-typescript2';
import replace from '#rollup/plugin-replace';
import { terser } from 'rollup-plugin-terser';
const packageJson = require('./package.json');
import { getFolders } from './scripts/buildUtils';
const plugins = [
peerDepsExternal(),
resolve(),
commonjs(),
typescript({
tsconfig: './tsconfig.json',
useTsconfigDeclarationDir: true,
}),
terser()
]
const getFolders = (entry) => {
// get the names of folders and files of the entry directory
const dirs = fs.readdirSync(entry)
// do not include folders not meant for export and do not process index.ts
const dirsWithoutIndex = dirs.filter(name => name !== 'index.ts').filter(name => name !== 'utils')
// ['Accordion', 'Button'...]
return dirsWithoutIndex
}
//loop through your folders and generate a rollup obj per folder
const folderBuilds = getFolders('./src').map(folder=> {
return {
input: `src/${folder}/index.ts`,
output: {
// ensure file destination is same as where the typings are
file: `dist/${folder}/index.js`,
sourcemap: true,
exports: 'named',
},
plugins,
external: ['react', 'react-dom'],
}
})
export default [
{
input: ['src/index.ts'],
output: [
{
file: packageJson.module,
format: 'esm',
sourcemap: true,
exports: 'named',
},
],
plugins,
external: ['react', 'react-dom'],
},
...folderBuilds,
{
input: ['src/index.ts'],
output: [
{
file: packageJson.main,
format: 'cjs',
sourcemap: true,
exports: 'named',
},
],
plugins,
external: ['react', 'react-dom'],
},
];
CJS file
finally i also added the rollup config to generate the cjs file. I did not bother to code split the cjs file since most users are using es6 imports
"frank" build
Post build, I run a script to copy paste package.json, Readme to the ./dist folder
/* eslint-disable no-console */
const { resolve, join, basename } = require('path');
const { readFile, writeFile, copy } = require('fs-extra');
const packagePath = process.cwd();
const distPath = join(packagePath, './dist');
const writeJson = (targetPath, obj) =>
writeFile(targetPath, JSON.stringify(obj, null, 2), 'utf8');
async function createPackageFile() {
const packageData = await readFile(
resolve(packagePath, './package.json'),
'utf8'
);
const { scripts, devDependencies, ...packageOthers } =
JSON.parse(packageData);
const newPackageData = {
...packageOthers,
private: false,
typings: './index.d.ts',
main: './main.js',
module: './index.js',
};
const targetPath = resolve(distPath, './package.json');
await writeJson(targetPath, newPackageData);
console.log(`Created package.json in ${targetPath}`);
}
async function includeFileInBuild(file) {
const sourcePath = resolve(packagePath, file);
const targetPath = resolve(distPath, basename(file));
await copy(sourcePath, targetPath);
console.log(`Copied ${sourcePath} to ${targetPath}`);
}
async function run() {
try {
await createPackageFile();
await includeFileInBuild('./README.md');
// await includeFileInBuild('../../LICENSE');
} catch (err) {
console.error(err);
process.exit(1);
}
}
run();
finally from root npm publish ./dist
This is how my dist folder looks like finally
dist
├── Accordion
│ ├── Accordion.d.ts
│ ├── AccordionBody.d.ts
│ ├── AccordionButton.d.ts
│ ├── AccordionCollapse.d.ts
│ ├── AccordionContext.d.ts
│ ├── AccordionHeader.d.ts
│ ├── AccordionItem.d.ts
│ ├── AccordionItemContext.d.ts
│ ├── index.d.ts
│ ├── index.js
│ └── index.js.map
├── Alert
│ ├── Alert.d.ts
│ ├── index.d.ts
│ ├── index.js
│ └── index.js.map
├── Badge
│ ├── Badge.d.ts
│ ├── index.d.ts
│ ├── index.js
│ └── index.js.map
├── Breadcrumb
│ ├── Breadcrumb.d.ts
│ ├── BreadcrumbItem.d.ts
│ ├── index.d.ts
│ ├── index.js
│ └── index.js.map
├── Button
│ ├── Button.d.ts
│ ├── index.d.ts
│ ├── index.js
│ └── index.js.map
├── ButtonGroup
│ ├── ButtonGroup.d.ts
│ ├── index.d.ts
│ ├── index.js
│ └── index.js.map
...
├── Tooltip
│ ├── Tooltip.d.ts
│ ├── TooltipBox.d.ts
│ ├── index.d.ts
│ ├── index.js
│ └── index.js.map
├── index.d.ts
├── index.js
├── index.js.map
├── main.js
├── main.js.map
├── package.json
I got my solutions after much research from rollup issue thread on gh.
Here are some references:
Franking the build : https://stackoverflow.com/questions/62518396/importing-from-subfolders-for-a-javascript-package#:~:text=Votes-,13,-This%20is%20possible
folder structuring :
https://github.com/ezolenko/rollup-plugin-typescript2/issues/136#issuecomment-792383946
inspiration for getFolders() that i wrote was from this author's getFiles()
https://www.codefeetime.com/post/rollup-config-for-react-component-library-with-typescript-scss/

PWA for website based on html not working

I am trying to integrate PWA into this html page https://moodmap.app/ .
I have used a manifest and created the service worker required - but it won't load for some reason?
directory layout below.
└── src
├── assets
│ ├── icons.svg
│ ├── images
│ │ ├── apple-touch-icon.png
│ │ ├── favicon.png
│ │ ├── image01.jpg
│ │ ├── image02.jpg
│ │ ├── _image02.svg
│ │ └── share.jpg
│ ├── LovelyChart.custom.js
│ ├── main.css
│ ├── main.js
│ ├── main_large.css
│ ├── main.min.js
│ ├── noscript.css
│ ├── noscript_other.css
│ └── videos
│ ├── video01.mp4
│ └── video01.mp4.jpg
├── example.html
├── index.html
├── manifest.json
├── pay.html
├── serviceworker.js
├── signup.html
└── stats.html
servicework.js
const staticMoodmap = "dev-MoodMap-site-v1"
const assets = [
"/",
"/index.html",
"/stats.html",
// "/signup.html",
// "/pay.html",
// "/assets/noscript.css",
// "/assets/main.css",
"/assets/main.min.js",
"/assets/LovelyChart.custom.js",
"/assets/icons.svg",
"/assets/images/image01.jpg",
"/assets/images/image02.jpg",
"/assets/images/share.jpg",
"/assets/images/_image02.svg",
"/assets/images/favicon.png",
"/assets/images/apple-touch-icon.png",
"/assets/videos/video01.mp4.jpg",
"/assets/images/video01.mp4",
]
self.addEventListener("install", installEvent => {
installEvent.waitUntil(
caches.open(staticMoodmap).then(cache => {
cache.addAll(assets)
})
)
})
self.addEventListener("fetch", fetchEvent => {
fetchEvent.respondWith(
caches.match(fetchEvent.request).then(res => {
return res || fetch(fetchEvent.request)
})
)
})
manifest.json
{
"name": "MoodMap",
"short_name": "MoodMap",
"start_url": "./index.html",
"display": "standalone",
"background_color": "#fdfdfd",
"theme_color": "#db4938",
"orientation": "portrait-primary",
"icons": [
{
"src": "/assets/images/image01.jpg",
"type": "image/jpg", "sizes": "72x72"
}
]
}
main.js
....
if ("serviceWorker" in navigator) {
window.addEventListener("load", function() {
navigator.serviceWorker
.register("./serviceworker.js")
.then(res => console.log("service worker registered"))
.catch(err => console.log("service worker not registered", err))
})
}
So I'm thinking that it has something to do with how I am integrating the javascript? or the directory structure?
I think the problem is on setting index.html because this link is not available
https://moodmap.app/index.html
So maybe you should change
"start_url": "./index.html"
You should change it to
"start_url": "/index.html"
Or
"start_url": "/"

Ember Module Unification Stack trace: Error: Assertion Failed: 'data-adapter' is not a recognized type

Ember data won't show on the inspector.The error is showing below.
I am using module unification in new ember. module unification ember
Can someone tell me how to fix it because I need to see data in ember inspector?
The data show an empty data which I see the model but there is nothing(image below):
Ember Inspector has errored.
This is likely a bug in the inspector itself.
You can report bugs at https://github.com/emberjs/ember-inspector.
Error message: Assertion Failed: 'data-adapter' is not a recognized type
Stack trace: Error: Assertion Failed: 'data-adapter' is not a recognized type
at assert (http://localhost:4200/assets/vendor.js:73088:19)
at Resolver._definitiveCollection (http://localhost:4200/assets/vendor.js:73063:31)
at Resolver.identify (http://localhost:4200/assets/vendor.js:73027:37)
at Resolver.resolve (http://localhost:4200/assets/vendor.js:73055:27)
at Class.resolve (http://localhost:4200/assets/vendor.js:98399:36)
at Class.resolve (http://localhost:4200/assets/vendor.js:98232:25)
at Class.superWrapper [as resolve] (http://localhost:4200/assets/vendor.js:41053:22)
at _resolve (http://localhost:4200/assets/vendor.js:12906:36)
at Registry.resolve (http://localhost:4200/assets/vendor.js:12445:21)
at Registry.resolve (http://localhost:4200/assets/vendor.js:12450:60)
warn # VM2062:92
handleError # VM2062:149
(anonymous) # VM2062:3515
_run # backburner.js:1066
run # backburner.js:748
run # index.js:111
wrap # VM2062:3511
messageReceived # VM2062:3482
get.onMessageReceived.message # VM2062:3476
get.forEach.callback # VM2062:127
_messageReceived # VM2062:126
run # VM2062:344
_run # backburner.js:1066
run # backburner.js:748
run # index.js:111
chromePort.addEventListener.event # VM2062:343
file tree:
src
├── data
│ └── models
│ ├── application
│ │ └── model.js
│ └── user
│ ├── adapter.js
│ └── model.js
├── formats.js
├── init
│ └── initializers
│ └── i18n.js
├── main.js
├── resolver.js
├── router.js
├── services
│ └── intl.ts
└── ui
├── components
├── index.html
├── routes
│ ├── about-page
│ │ ├── route.js
│ │ └── template.hbs
│ ├── application
│ │ ├── controller.js
│ │ ├── route.js
│ │ └── template.hbs
│ └── user
│ ├── controller.js
│ ├── route.js
│ └── template.hbs
├── styles
│ └── app.css
└── utils
This is the file structure of the module unification. There is nothing special in the package.json.
After adding those configuration (from #NullVoxPopuli) to the resolver.js
"data-adapter": { definitiveCollection: "main" },
"container-debug-adapter": { definitiveCollection: "main" },
"resolver-for-debugging": { definitiveCollection: "main" }
assign(moduleConfig.collections, {
data: { types: ["data-adapter", "model"], defaultType: "model" }
});
This is def one of the rougher parts of module unification at the moment.
So far, I've been able to get the data tab on the inspector to be loaded with this resolver config:
import Resolver from 'ember-resolver/resolvers/fallback';
import buildResolverConfig from 'ember-resolver/ember-config';
import config from '../config/environment';
let moduleConfig = buildResolverConfig(config.modulePrefix);
moduleConfig.types = Object.assign(moduleConfig.types, {
// ember-inspector support
'data-adapter': { definitiveCollection: 'main' },
'container-debug-adapter': { definitiveCollection: 'main' },
'resolver-for-debugging': { definitiveCollection: 'main' },
});
moduleConfig.collections.main.types.push('data');
moduleConfig.collections = Object.assign(moduleConfig.collections, {
data: {
types: ['data-adapter', 'model'],
defaultType: 'model',
},
});
export default Resolver.extend({
config: moduleConfig,
});
with this config, the models are only picked up if they are named in src/data/models/{model-name}.js -- if a model is at src/data/models/{model-name}/model.js, this does not tell the inspector where to look.

How to load into specific path

i have an app directory looks like
app/
├── controllers
│   ├── index.js
│   └── users.js
├── errors.js
├── models
│   └── user.js
└── other_things
in the server.js i have the following code using express-load
load('errors', {cwd: 'app'})
.then('models')
.then('controllers')
.into(app);
but console.log(app.errors) is undefined
and console.log(app); show the following among many other unrelated output
'': { errors: { not_found: [Function] } } }
how do i convert that to be
'errors':{ not_found: [Function] } }
the errors.js is defined as following
exports.not_found = function(err){
//... yada yada...
}
this solution work prior to express-load 1.1.14:
load('app/errors').into(app, function(err, instance){
app.errors = app.app.errors;
delete app.app;
});
load('models', {cwd: 'app'}).then('controllers').into(app);
and it was fixed in version 1.1.14

Categories