Firebase database how to list - javascript

I am trying to query a Firebase database. I have the following code, but it returns an empty list, when there is matching data.
loadData() {
this.firelist = this.af.database.list('/chat/', {
query: {
orderByChild: 'negativtimestamp'
}
}).map(items => {
const filtered = items.filter(item => {
item.memberId1 === this.me.uid;
});
return filtered;
});
// if me not in firelist then create new chat
if (this.me && this.me.uid) {
let chatFound: boolean = false;
console.log('this.firelist', this.firelist);
this.firelist.forEach(chatItems => {
console.log('chatItems', chatItems);
for (let i = 0; i < chatItems.length; i++) {
console.log('chatItems['+i+']', chatItems[i]);
let memberId1: string = chatItems[i].memberId1;
let memberId2: string = chatItems[i].memberId2;
if (memberId1 === this.me.uid || memberId2 === this.me.uid) {
chatFound = true;
break;
}
}
if (!chatFound) {
//this.createChat();
}
});
}
}
I think my problem is with the filter.
The following code creates a chat successfully:
createChat(img1: string, img2: string) {
this.af.database.list('/chat/').push({
memberId1: this.me.uid,
memberId2: this.you.uid,
img1: img1,
img2: img2,
displayName1: this.me.displayName,
displayName2: this.you.displayName,
lastMsg_text: 'todo',
timestamp: Date.now(),
negativtimestamp: -Date.now()
})
}

The following filter works:
this.firelist = this.af.database.list('/chat/', {
query: {
orderByChild: 'negativtimestamp'
}
}).map(items => {
const filtered = items.filter(
item => item.memberId1 === this.me.uid
);
return filtered;
});

Related

pass an argument from axios to a method vue

I'm new to vue and I'm trying to make this work. I get some data from a XML, everything works, but I want to change which value I get from XML using a computed which gets a value from Store.
My computed is:
currentStep: {
set (val) {
this.$store.commit('setCurrentStep', val)
},
get () {
return this.$store.state.currentStep
}
}
With axios and xml2js I get all data with this Method:
getData() {
axios.get("https://something.xml").then((response) => {
this.parseXML(response.data).then((data) => {
this.flightInformations = data
})
})
},
parseXML(data) {
return new Promise((resolve) => {
let parser = new xml2js.Parser({
trim: true,
explicitArray: true,
});
parser.parseString(data, function (err, result) {
let obj = null
obj = result.flugplan.abflug[0].flug;
let flight_dates = {};
for (let item of obj) {
let flight_date = item.datum.join().toString();
if (!flight_dates[flight_date]) {
flight_dates[flight_date] = [];
}
flight_dates[flight_date].push({
flightNr: item.flugnr.join().toString(),
flightPlace: item.ort.join().toString(),
flightPlan: item.plan.join().toString(),
flightExpected: item.erwartet.join().toString(),
flightDate: item.datum.join().toString(),
})
}
resolve(flight_dates);
})
})
}
I need to change my OBJ using my computed like:
let obj = null
if (this.currentStep === 'departures') {
obj = result.flugplan.abflug[0].flug;
} else {
obj = result.flugplan.ankunft[0].flug;
}
But it does not work. Can you guys please help ?
Thank you very much.
Computed can only return some value instead of modifying anything.
Try this one:
computed: {
someData() {
return this.currentStep === 'departures' ? result.flugplan.abflug[0].flug : result.flugplan.ankunft[0].flug;
}
}
After that use a someData value:
const obj = this.someData
I get it finally and now works! here is the code, if someone have the same issue
getData() {
axios.get("something.xml").then((response) => {
this.parseXML(response.data).then((data) => {
this.flightInformations = data
})
.catch(err => {
console.log(`${err} data is not avaiable`)
})
})
},
parseXML(data) {
return new Promise((resolve) => {
let parser = new xml2js.Parser({
trim: true,
explicitArray: true,
});
parser.parseString(data, (err, result) => {
let obj = null
if (this.$store.state.currentStep === 'abflug') {
obj = result.flugplan.abflug[0].flug
} else {
obj = result.flugplan.ankunft[0].flug
}
let flight_dates = {};
for (let item of obj) {
let flight_date = item.datum.join().toString();
if (!flight_dates[flight_date]) {
flight_dates[flight_date] = [];
}
flight_dates[flight_date].push({
flightNr: item.flugnr.join().toString(),
flightPlace: item.ort.join().toString(),
flightPlan: item.plan.join().toString(),
flightExpected: item.erwartet.join().toString(),
flightDate: item.datum.join().toString()
})
}
resolve(flight_dates)
})
})
}
Now using Store, when I change my CurrentStep, it also changes which part of XML it reads.

how i can get a value through key

i want to know how i can get a value/numbers through key/username ?
look like that console.log(acc.${username})
my js
...
app.get("/account", (req, res) => {
loggedIn = req.cookies.loggedIn;
username = req.cookies.username;
if (loggedIn == "true") {
db.list().then(keys => {
if (keys.includes(username)) {
res.render("settings.html", { username: username })
var data = fs.readFileSync('2FA.json');
var acc = JSON.parse(data)
//////////////////////////////////////////////
console.log(acc.${username}) // i want to see a numbers in user name look like in here
/////////////////////////////////////////////
} else {
res.redirect("/logout");
}
});
} else {
res.render("notloggedin.html");
}
});
my json
[
{
"youssefnageeb": 927342
},
{
"youssefnageeb1":310686
},
{
"youssefnageeb2": 105380
},
{
"youssefnageeb3": 431816
},
{
"youssefnageeb4": 484728
}
]
I am guessing "data" is in the format mentioned above.
So, you can do
const index = data.findIndex(function isAccountRow(row) { return typeof row[username] === 'number'; })
if(index === -1) {
return res.redirect("/logout");
}
const row = data[index];
console.log(row[username]); // will be the number

Changing from local storage to a databse

I have a kanban site which stores the data in the local storage of the browser , I know the data I have stored would be stored in the specific browser that I'm using and if I open another browser the data will not be there , Is there an easy way to change from the local storage of the browser into something else which would allow me to access the data into all browsers ?
or is there an easy way to modify my code in order for it to work for all browsers ?
Class :
export default class KanbanAPI {
static getItems(columnId) {
const column = read().find(column => column.id == columnId);
if (!column) {
return [];
}
return column.items;
}
static insertItem(columnId, content) {
const data = read();
const column = data.find(column => column.id == columnId);
const item = {
id: Math.floor(Math.random() * 100000),
content
};
if (!column) {
throw new Error("Column does not exist.");
}
column.items.push(item);
save(data);
return item;
}
static updateItem(itemId, newProps) {
const data = read();
const [item, currentColumn] = (() => {
for (const column of data) {
const item = column.items.find(item => item.id == itemId);
if (item) {
return [item, column];
}
}
})();
if (!item) {
throw new Error("Item not found.");
}
item.content = newProps.content === undefined ? item.content : newProps.content;
// Update column and position
if (
newProps.columnId !== undefined &&
newProps.position !== undefined
) {
const targetColumn = data.find(column => column.id == newProps.columnId);
if (!targetColumn) {
throw new Error("Target column not found.");
}
// Delete the item from it's current column
currentColumn.items.splice(currentColumn.items.indexOf(item), 1);
// Move item into it's new column and position
targetColumn.items.splice(newProps.position, 0, item);
}
save(data);
}
static deleteItem(itemId) {
const data = read();
for (const column of data) {
const item = column.items.find(item => item.id == itemId);
if (item) {
column.items.splice(column.items.indexOf(item), 1);
}
}
save(data);
}
}
function read() {
const json = localStorage.getItem("kanban-data");
if (!json) {
return [
{
id: 1,
items: []
},
{
id: 2,
items: []
},
{
id: 3,
items: []
},
];
}
return JSON.parse(json);
}
function save(data) {
localStorage.setItem("kanban-data", JSON.stringify(data));
}

How to push object into array angular 8

i am getting below example data in this.selectedParameterContext.
Please try the below code.
deleteAllContextData(data) {
const newSelectedParameterContext = {
'records': []
};
this.selectedParameterContext.records.forEach(function (record) {
const newSelectedParameterValues = [];
record.values.forEach(function (parameter, parameterIndex) {
const isValid = data.data.values.find(function (item) {
return parameter.value === item.value && parameter.label === item.label;
});
if (isValid) {
newSelectedParameterValues.push(parameter);
}
});
newSelectedParameterContext.records.push({ ...record, 'values': newSelectedParameterValues });
});
this.selectedParameterContext = newSelectedParameterContext;
}

Vue test utils: TypeError mounted

I am having an issue with Vue Test Utils. When I run a unit test, I am always confronted with:
TypeError{line: 73983, sourceURL: 'http://localhost:9876/base/index.js?045b00affe888fcd6b346c4fe50eadd13d471383', stack: 'mounted#http://localhost:9876/base/index.js?045b00affe888fcd6b346c4fe50eadd13d471383:73983:30.....
This only happens when I have the mounted() function in the Vue component
Settings.vue
mounted() {
this.$refs.address.update(this.profile.address)
},
Settings.spec.js
it('calls updateUserInformation before mount', () => {
const spy = sinon.spy(Settings.methods, 'updateUserInformation')
shallow(Settings, { propsData })
Vue.nextTick().then(() => {
spy.should.have.calledOnce()
})
})
I am using Mocha & Chai with vue-test-utils. Does anyone know why this is happening?
Thank you in advance!
UPDATE
Settings.vue component HTML
<vue-google-autocomplete
ref="address"
id="map"
classname="input"
placeholder="Address"
v-on:placechanged="getAddressPlaceChanged"
v-on:inputChange="getAddressInputChange"
:country="['sg']"
>
</vue-google-autocomplete>
Settings.vue component Javascript
export default {
components: {
GoogleMaps,
AutoComplete,
VueGoogleAutocomplete,
Partner,
},
watch: {
// whenever school changes, this function will run
school() {
// Check if school value is an empty string or character is lesser than FIX_STR_LENGTH
if (this.school === '' || this.school.length < this.FIX_STR_LENGTH) {
this.removeMarker('school')
}
this.fetchSchools()
},
},
methods: {
async onSubmit() {
// Check if input fields are empty
if (this.address !== undefined && this.phoneNumber !== null && this.school !== '') {
const { placeResultData = {}, addressData = {} } = this.address
let isSuccessful = false
let tempLat = null
let tempLong = null
let tempAddress = null
// Check if address is an empty object
if (_.isEmpty(this.address)) {
const { latlong = {}, address = '' } = this.profile
const [lat, long] = latlong.coordinates
tempLat = lat
tempLong = long
tempAddress = address
} else {
// User changed address location
tempLat = addressData.latitude
tempLong = addressData.longitude
tempAddress = placeResultData.formatted_address
}
// Validate school address array
let tempSchoolAddress = []
if (this.selectedSchool !== null) {
tempSchoolAddress.push(this.selectedSchool.postal_code)
} else {
tempSchoolAddress = this.profile.schoolAddress
}
// Construct user object for registration/update
const user = new User(
this.profile.name,
tempAddress,
tempLat,
tempLong,
tempSchoolAddress,
)
// If user does not exist in database, perform a POST API registration request
if (this.userExist === false) {
// Add user properties for user registration
user.phoneNumber = this.phoneNumber
await UserSession.register(user, localStorage.getItem('id_token')).then((response) => {
const { data = {} } = response
const profile = data.user
this.updateUserInformation(profile)
isSuccessful = true
this.profile = profile
}).catch((error) => {
console.log(error.response)
})
}
// Perform a PUT API update request
await UserSession.update(user, localStorage.getItem('id_token')).then((response) => {
const { data = {} } = response
const profile = data.user
this.updateUserInformation(profile)
isSuccessful = true
this.profile = profile
}).catch((error) => {
console.log(error.response)
})
if (isSuccessful) {
this.profileChanged()
this.hasChanged = true
}
}
},
profileChanged() {
this.$emit('profileChanged', this.profile)
},
addMarker(name, params) {
if (params === null || params === '') {
return
}
gMapSession.default(params).then((response) => {
const { location = {} } = response.data.results[0].geometry
// Remove existing marker before replacing it
this.removeMarker(name)
this.markers.push({
position: location,
name,
})
this.zoom = 11
}).catch((error) => {
console.log(error.response)
})
},
removeMarker(name) {
let index = 0
let exist = false
for (let i = 0; i < this.markers.length; i++) {
if (this.markers[i].name === name) {
index = i
exist = true
break
}
}
if (exist) {
this.markers.splice(index, 1)
}
},
// Function called when user selects an option from the school autocomplete dropdown
getSelectedSchoolData(event) {
this.selectedSchool = event
// Check if selected school is defined
if (this.selectedSchool !== undefined && this.selectedSchool !== null) {
this.addMarker('school', this.selectedSchool.postal_code)
} else {
this.removeMarker('school')
}
},
// Function called when user types in the address autocomplete input field
getAddressInputChange(data) {
const { newVal = {} } = data
if (newVal === '' || newVal.length < this.FIX_STR_LENGTH) {
this.removeMarker('user')
}
},
// Function called when user selects an option from the address autocomplete dropdown
getAddressPlaceChanged(addressData, placeResultData) {
this.address = {
placeResultData,
addressData,
}
if (addressData !== undefined && addressData !== null) {
this.addMarker('user', addressData.postal_code)
} else {
this.removeMarker('user')
}
},
async updateUserInformation(profile) {
this.phoneNumber = profile.phoneNumber
this.addMarker('user', profile.address)
// TODO: schoolAddress is an array and UI must cater to multiple schools
await SchoolSession.default(profile.schoolAddress[0]).then(async (res) => {
const { result = {} } = res.data
const { records = [] } = result
// Assume that a single postal code contains only 1 school
this.school = records[0].school_name
this.addMarker('school', records[0].postal_code)
})
},
// Fetch school information base on school search query
fetchSchools: _.debounce(function getSchools() {
if (this.school.trim() === '') {
this.schools = []
return
}
const vm = this
SchoolSession.default(this.school).then((response) => {
// JSON responses are automatically parsed.
const { records = {} } = response.data.result
vm.schools = records
}).catch((error) => {
console.log(error.response)
})
}, 500),
},
data() {
return {
FIX_STR_LENGTH: 5,
school: '',
address: '',
schools: [],
markers: [],
phoneNumber: null,
selectedSchool: null,
userExist: false,
hasChanged: false,
center: { lat: 1.3521, lng: 103.8198 },
zoom: 7,
}
},
async created() {
this.profile = this.$attrs
// Check if user was a registered member by phone number
if (this.profile.phoneNumber === undefined) {
return
}
// User exist in the database
this.userExist = !this.userExist
// Update form information
this.updateUserInformation(this.profile)
},
mounted() {
this.$refs.address.update(this.profile.address)
},
}

Categories

Resources