I am creating a note taking app and am getting stuck on my deleteNote function. I am needing to use the .filter method to remove notes w/ an assigned id and keep the ones not associated to that id. Here is my code so far.
const fs = require("fs");
const util = require("util");
// returns a unique ID for our returns
const uuidv1 = require("uuid/v1");
// creates a promified version of fs.readfile and writefile
const readFileAsync = util.promisify(fs.readfile);
const writeFileAsync = util.promisify(fs.writefile);
class Store {
read() {
return readFileAsync("./db/db.json", "utf8");
}
write(note) {
return writeFileAsync("./db/db.json", JSON.stringify(note));
}
getNotes() {
return this.read().then(notes => {
let parsedNotes;
try {parsedNotes = [].concat(JSON.parse(notes))}
catch (err) {
parsedNotes = [];
}
return parsedNotes;
})
}
// example of destructuring -- im taking the title, text string and destructuring it to add a unique id.
addNote(note) {
const {title, text} = note;
const newNote = {title, text, id: uuidv1()};
return this.getNotes()
.then(notes => [...notes, newNote]);
.then(updatedNotes => this.write(updatedNotes));
.then(() => newNote);
}
// delete note is going to take in an id and use a .filter to only keep the notes that do not include that id.
deleteNote() {
}
}
module.exports = new Store();
You already know you're filtering, so just do it:
deleteNote(id) {
return this.getNotes()
.then(notes => notes.filter(note => note.id !== id))
.then(updatedNotes => this.write(updatedNotes));
}
Try this one which includes returning deleted note.
async deleteNote(id) {
const notes = await this.getNotes();
const filtered = notes.filter((note) => note.id !== id);
await this.write(filtered);
const deleted = notes.filter((note) => note.id === id);
return deleted;
}
Related
Hello so I have images in a mongodb database and I'm trying to render them on the client side however It's not working. I convert the buffer unit8 data into base64 so I can render it it seemd to work and been stored in the images state but images are not accessible by associative array.
useEffect( () => {
const getAllDoctors = async () => {
const result = await api.get('doctor/all')
const myImages = []
setDoctors(result.data)
await result.data.forEach(async doctor => {
myImages[doctor._id] = await base64_arraybuffer(doctor.photo.data.data)
})
setImages(myImages)
setLoading(false)
}
getAllDoctors()
}, [])
as for the render
return (
<div>
{
images.map((image, key) => {
console.log(doctors)
return (
<div key={key}>
<img alt={'image'} src={`data:image/png; base64, ${image}`}/>
<div>{`Doctor + ${images}`}</div>
</div>
)
})
}
</div>
);
converter (not mine):
const base64_arraybuffer = async (data) => {
const base64url = await new Promise((r) => {
const reader = new FileReader()
reader.onload = () => r(reader.result)
reader.readAsDataURL(new Blob([data]))
})
return base64url.split(",", 2)[1]
}
Two things
The way your array assignment is doesn't make sense. If _id is a ID string, then you are using a string to key an array, the data assigned at that key won't be included in loops. Use Array.prototype.push to add the item to the next available index.
Array.prototype.forEach and async / await don't play nice together due to the nature of callbacks. Try using a traditional loop.
useEffect(() => {
const getAllDoctors = async () => {
const result = await api.get("doctor/all");
const myImages = [];
setDoctors(result.data);
for (const doctor of result.data) {
const image = await base64_arraybuffer(doctor.photo.data.data);
myImages.push(image)
}
setImages(myImages);
setLoading(false);
};
getAllDoctors();
}, []);
How can i return single object for instead of array? Because i asking in api just for single "Event" I using MongoDB + Next.js
I always getting
[{}]
i Just want it get
{}
const fetchWithId = (url: RequestInfo) => fetch(url).then((r) => r.json());
const index = () => {
const router = useRouter();
const { data, error } = useSWR(
`http://localhost:3000/api/events/event?slug=${router.query.slug}`,
fetchWithId
);
Here is a Next API
const handler = async (req: NextApiRequest, res: NextApiResponse) => {
const {
method,
query: { slug},
} = req;
if (req.method !== 'GET') {
return;
}
await dbConnect();
const selectedEvent = await Events.find({
slug: slug,
});
res.status(200).json(selectedEvent);
};
export default handler;
You would want to call the method .findOne() rather than .find():
const selectedEvent = await Events.findOne({
slug: slug
});
I want the result of activeCustomers array inside the last then but I keep getting an error saying arrow function expects a return. Not sure how I can get activeCustomers?
const CreateCustomer = (storeData) => {
let activeOrganization = null;
storeData.Org
.getOrganization()
.then(function createCustomer(organization) {
activeOrganization = organization[0];
const dataArray= storeData.attributes;
activeOrganization
.createAttributes(
attributeType[0],
getSomeData(dimensions)
)
.then(function Properties(createdAttribute) {
updateCustomerProperty(createdAttribute, attributeType[0]);
});
activeOrganization
.createAttributes(
attributeType[1],
getSomeData(dimensions)
)
.then(function Properties(createdAttribute) {
updateCustomerProperty(createdAttribute, attributeType[1]);
});
}).then(() => {
activeOrganization
.getCustomers()
.then((cusomters) => {
const activeCustomers = [];
cusomters.map((customer) => {
activeCustomers.push(customer);
});
return activeCustomers;
})
.then((activeCustomers) => {
console.log(activeCustomers);
});
});
};
//Now I want the result of activeCustomers array inside the last then but I keep getting an error saying arrow function expects a return. Not sure how I can get activeCustomers?
I want the result of activeCustomers array inside the last then but I keep getting an error saying arrow function expects a return. Not sure how I can get activeCustomers?
In your example i think you received a warning. But still how to access to activeCustomers it depends on how you want to use it there are you storing it.
If you want to store it globally then you can store it like that
let activeCustomers;
....
.then((cusomters) => {
activeCustomers = [];
cusomters.map((customer) => {
activeCustomers.push(customer);
});
return activeCustomers;
})
But i think it's better to rewrite to async/await.
const CreateCustomer = async (storeData) => {
let activeOrganization = null;
const [activeOrganization] = await storeData.Org
.getOrganization();
const activeOrgPrs = attributeType.map(x => activeOrganization
.createAttributes(
x,
getSomeData(dimensions)
)));
const attrs = await Promise.all(activeOrgPrs);
attrs.forEach((attr, i) => {
updateCustomerProperty(attr, attributeType[i]);
})
const cusomters = await activeOrganization
.getCustomers();
return cusomters;
};
And you can use it like const customers = await CreateCustomer(someData);
or like CreateCustomer(someData).then((cusomters) => { activeCustomers = cusomters; return null;(if it keeps to return errors)});
I am new to cloud funcations node.js and type script. I am running the below code and getting the error below and can't make sense of it after watch a ton of videos about promises and searching other questions.
any help would be appreciated.
Function returned undefined, expected Promise or value
exports.compReqUpdated = functions.firestore
.document('/compRequests/{id}')
.onUpdate((change, contex)=>{
const newData = change.after.data();
//const oldData = change.before.data();
const dbConst = admin.firestore();
const reqStatus:string = newData.requestStatus;
const compId:string = newData.compID;
const reqActive:boolean = newData.requestActive;
if (reqStatus == "CANCELED" && reqActive){
const query = dbConst.collection('compRequests').where('compID', '==', compId);
const batch = dbConst.batch();
query.get().then(querySnapshot => {
const docs = querySnapshot.docs;
for (const doc of docs) {
console.log(`Document found at path: ${doc.ref.path}`);
console.log(doc.id);
const docRef = dbConst.collection('compID').doc(doc.id);
batch.update(docRef, {requestStatus: 'CANCELED',requestActive: false});
};
return batch.commit()
})
.catch(result => {console.log(result)});
}else{
return
}
});
The firebase docs state that the callback passed to the onUpdate function should return PromiseLike or any value, but you aren't returning anything right now. If you change your code to something as follows I reckon it should work as expected:
exports.compReqUpdated = functions.firestore
.document('/compRequests/{id}')
.onUpdate((change, contex) => {
const newData = change.after.data();
//const oldData = change.before.data();
const dbConst = admin.firestore();
const reqStatus: string = newData.requestStatus;
const compId: string = newData.compID;
const reqActive: boolean = newData.requestActive;
if (reqStatus == "CANCELED" && reqActive) {
const query = dbConst.collection('compRequests').where('compID', '==', compId);
const batch = dbConst.batch();
return query.get().then(querySnapshot => {
const docs = querySnapshot.docs;
for (const doc of docs) {
console.log(`Document found at path: ${doc.ref.path}`);
console.log(doc.id);
const docRef = dbConst.collection('compID').doc(doc.id);
batch.update(docRef, { requestStatus: 'CANCELED', requestActive: false });
};
return batch.commit()
}).catch(result => { console.log(result) });
} else {
return false;
}
});
Can someone provide an example on how to use the beforeEach? http://www.node-tap.org/api/
Ideally, an example of the promise version, but a callback version example would also be nice.
Here is a test I created which works fine:
'use strict';
const t = require('tap');
const tp = require('tapromise');
const app = require('../../../server/server');
const Team = app.models.Team;
t.test('crupdate', t => {
t = tp(t);
const existingId = '123';
const existingData = {externalId: existingId, botId: 'b123'};
const existingTeam = Team.create(existingData);
return existingTeam.then(() => {
stubCreate();
const newId = 'not 123'
const newData = {externalId: newId, whatever: 'value'};
const newResult = Team.crupdate({externalId: newId}, newData);
const existingResult = Team.crupdate({externalId: existingId}, existingData);
return Promise.all([
t.equal(newResult, newData, 'Creates new Team when the external ID is different'),
t.match(existingResult, existingTeam, 'Finds existing Team when the external ID exists')
]);
});
})
.then(() => {
process.exit();
})
.catch(t.threw);
function stubCreate() {
Team.create = data => Promise.resolve(data);
}
Before I do anything, I want to persist existingTeam. After it's saved, I want to stub Team.create. After these two things, I want to start actually testing. I think it would be cleaner if instead of using a Promise.all or perhaps duplicating the test code, I could use beforeEach.
How would I convert this to use beforeEach? Or what is an example of its usage?
Simple, just return promise from callback function
const t = require('tap');
const tp = require('tapromise');
const app = require('../../../server/server');
const Team = app.models.Team;
const existingId = '123';
const existingData = {
externalId: existingId,
botId: 'b123'
};
t.beforeEach(() => {
return Team.create(existingData).then(() => stubCreate());
});
t.test('crupdate', t => {
t = tp(t);
const newId = 'not 123'
const newData = {
externalId: newId,
whatever: 'value'
};
const newResult = Team.crupdate({
externalId: newId
}, newData);
const existingResult = Team.crupdate({
externalId: existingId
}, existingData);
return Promise.all([
t.equal(newResult, newData, 'Creates new Team when the external ID is different'),
t.match(existingResult, existingTeam, 'Finds existing Team when the external ID exists')
]);
}).then(() => {
process.exit();
}).catch(t.threw);
function stubCreate() {
Team.create = data => Promise.resolve(data);
}