pouchdb inline attachment - saving and retrieving - javascript

I'm trying to use pouchdb to save an image which has been encoded in base64 format as an attachment against a document (inline) and then retrieve it again.
However, when i retrieve the document it seems as though pouchdb has modified the base64 image data and has appended 'md5-' to it. There is also no 'data' attribute off of the attachment object, as i would have expected. Instead i find an object called 'digest'. What is this?
I have created an example:
var db = new PouchDB('example');
db.bulkDocs(
[
{
_id: '1',
name: 'example',
"_attachments": {
"avatar.jpg": {
"content_type": "image/jpg",
"data": [BASE65 DATA STRING]
}
}
],
function(err, response) {
if (!err) {
db.allDocs({ include_docs: true, attachments: true }, function(err, docs) {
var d = docs.rows[0].doc;
// d looks like this:
// {"name":"example","_attachments":{"avatar.jpg":{"content_type":"image/jpg","digest":"md5-57e396baedfe1a034590339082b9abce","stub":true}},"_id":"1","_rev":"1-ff23a959ae88b871b94374a784a07728"}
});
}
}
);
Full example can be found here: http://jsfiddle.net/ntan0ycL/
How would i go about retrieving the base64 representation of the image from the pouchdb document? I'm not sure if the problem lies in how i'm saving the attachment or how i'm retrieving it.
Thanks,
Andrew.

Looks like we made a mistake, and the allDocs() API doesn't support the attachments option. So what you're getting back is just an attachments stub.
I've filed an issue: https://github.com/pouchdb/pouchdb/issues/2771
In the meantime, you can use the normal getAttachment() or get() API with {attachments: true} to fetch the attachments individually. Sorry about that.

Related

What do I return from the query function of datasource.js for grafana log panel datasource plugin?

I am trying to reproduce the steps given in grafana log data source plugin
so that I can replace the current-query function with a hardcoded log-panel compatible query function
in oci-datasource-plugin
Github link| oci-datasource-file
From the documentation of log-panel build guide
const frame = new MutableDataFrame({
refId: query.refId,
fields: [
{ name: 'time', type: FieldType.time },
{ name: 'content', type: FieldType.string, labels: { filename: 'file.txt' } }
],
});
frame.add({ time: 1589189388597, content: 'user registered' })
frame.add({ time: 1589189406480, content: 'user logged in' })
The documentation suggests to return a Frame.
The steps given shows a Mutable data frame.
But the panel expects a response.
If a frame is returned instead of a response data, the following error appears
Based on the working code found in Github link| oci-datasource-file
for a different panel type , I modified my code to return a response with data inside it.
My response look this and replacing the data with
result.data = frame.toJSON()
return result
Also, if you can paste a working sample data that I can look at , it will be really helpful.
To be more precise, I am looking for the sample json data for log panel
After looking into one of the test files in Grafana | LogDetails.test.tsx
Looks, like it must be returned must be returned as
result.data = [frame]
return result

Loopback4 - How to upload file to POSTS model

I'm using Loopback4 to create a sort-of blog api. My posts model will contain an image (or perhaps several in the future).
What i'm trying to do is -> upload image when creating a new post.
I've read quite a few articles regarding this, but since i'm new to nodejs and loopback4 i'm having a bit of trouble making it work.
I've followed the answer written here Loopback 4: Upload multipart/form-data via POST method and i'm encountering some problems with it.
First: I'm using MySQL. Is there any way to save the image in the database? Or is it not a good practice? The work-around would be to upload the image and save only the image location in the DB.
Second: After following the tutorial and ending up with the code created i made a new post request for testing purposes. It looks something like this.
#post('/posts/upload', {
responses: {
'200': {
description: 'Post model instance',
content: { 'application/json': { schema: { type: 'object' } } },
},
},
})
async uploadFile(#requestBody({
description: 'multipart/form-data value.',
required: true,
content: {
[FORM_DATA]: {
schema: { 'media-type': Post },
},
},
})
body: unknown,
) {
return body;
}
That creates my post request in Swagger, but it shows like a big input box (text input). As far as i know swagger supports upload button. Is the content-type wrong? How could i test my upload function? I did something similar in NetCore2 and i had to convert my image to bytes (if i remember correctly), is the same problem here?
Any tips? Thanks!

File converting into empty array on angular to laravel post request

I'm trying to perform a basic Laravel 5 post request which simply do the following:
Save some data into a database
Stores a file (image) into public storage under a name which is a possible combo of 20 random numbers following '.jpg'
Save a url (which is used to locate the image in an img tag. I'm aware this isn't the best approach so feel free to post)
However, when performing an ordinary post request with no special headers from angular 6 to laravel 5, for some reason the File keeps converting into an empty array. (Before and after shots are below)
Before:
0: Object { id: 0, body: null, file: File }
After:
0: Object { id: 0, body: null, file: [] }
The File is full and is used to create a preview on a canvas before submitting so It works. The console is logging this data the line before posting and returning the $req Request before performing any php code in Laravel.
So the only place anything could get lost in translation is the in between. Code is as follows:
Angular 6:
postToLaravel(object) {
console.log(object.message);
this.http.post(this.url + '/add/message', object).subscribe(res => {
console.log(res);
});
}
Laravel 5:
function addMessage(Request $req) {
return $req->messages;
The empty array keeps pushing nothing to storage under a name its registered as a jpg file but no image is shown.
On the component that images are uploaded we have the following block take place after a (change)="" event:
onFileSelected(e: any) {
this.sectedFile = e.target.files[0];
this.isImage = true;
this.messageService.addImage(this.id, this.sectedFile);
this.preview();
}
The service function just finds the right object and adds a file:
addImage(id, file) {
var index = this.data.findIndex(x => x['id'] == id);
this.data[index]['body'] = null;
this.data[index]['file'] = file;
}
And when the submit button is pressed it just takes all the variables in the service and compacts them into an object. this object contains messages which is an array of further objects (the objects are as shown at the top) (If that made sense)
pushMessageToServer() {
this.messageService.postToLaravel({
title: this.title,
location: this.location,
gender: this.gender,
age: this.age,
deadline: this.deadline,
messages: this.data
});
}
Is there something I'm missing here?
Let me know should You need any extra info.
Turns out images in FormData are passed through and displayed as empty objects in the console. I just needed to know how to grab them. Thanks for your help everyone

Cant send the result of find query (on an array of obj ids) with ejs

I'm trying to send some data along with my ejs file. The data I need to send is an array of json. I've tried using the code below but i'm confused as to why it's not working when I try to send the result of my query.
I've used the following code
var objIds = [obj_id1, obj_id2....] //assume these are object ids
Model.find({
_id : {
$in: objIds
}
}, function(err, doc){
console.log(doc); //doc returns an array of json
var test = [{
"hi":"bye"
}];
res.render('index', arrayOfResults: test});
});
The above code works when I send test but it gives me many errors on the client side when I send doc (the result of the find query). Both test and doc are array of json yet only test works without errors. Does anyone know why?
edit: i should note that the json inside doc would have the following format:
{
field1: [object]
field2: String
}

A Simple Way To Edit And Delete files in a directory in Node.js?

Hello I'm creating a simple blog using express.js, using a data.json file to create/update/delete, posts based on the id.
And every time I do that, I use fs.writeFile to create and update markdown posts using the slug data in the json array.
So when I create a post named First Post, I get a first-post.md file on my /path folder.
The Problem: Every time I'm updating a file and use fs.writeFile I'm creating a new file path without deleting the old one?
Example:
Updating the name data on the json array:
first post
to
first post update
I get a markdown file first-post-update.md.But the old first-post.md file still exists.
Is it possible to delete every markdown file on a directory path that doesn´t have a corresponding link to each slug data in the data.json file?
Something like this:
function deleteFiles(files, callback){
files.forEach(function(filepath){
//Filter every item.id on data.json and get the slug params.
fs.unlink(filepath, function(err) {
//If any markdown file don´t have a corresponding link to each slug data delete them.
});
}
data.json example:
{
"posts": [
{
"name": "First Post",
"desc": "Some description",
"slug": "first-post",
"id": "07cbc3854-7fa7-4451-883c-a9c8c87143ef"
}
]
}
some example code to create and update posts:
exports.save = function (req, res) {
var slugTitle = slug(req.body.name).toLowerCase().split('.').join("");
var description = req.body.desc;
db.add({name:req.body.name, desc:req.body.desc, slug: slugTitle});
fs.writeFile("path/"+slugTitle+".md", description, function(err) {
if(err) {
console.log(err);
} else {
console.log("The new post was created on path/"+slugTitle+".md");
}
});
res.redirect('/post');
};
exports.update = function (req, res) {
var slugTitle = slug(req.body.name).toLowerCase().split('.').join("");
var description = req.body.desc;
db.update({id: req.body.id, name: req.body.name, desc: req.body.desc,slug: slugTitle});
fs.writeFile("path/"+slugTitle+".md", description, function(err) {
if(err) {
console.log(err);
} else {
console.log("The new post was updated on path/"+slugTitle+".md");
}
});
res.redirect('/post');
};
Have you considered removing the old markdown file as part of the update process? You could retrieve the slugTitle from the document in the database prior to updating it, and then delete that file. I've outlined an example below, you could make this another function or integrate it directly into your update function. You'd want to put some thought into what will work best in your code, without too many layered callbacks.
Note that I'm using findById from Mongoose, but you could apply the concept to whatever system you're using.
db.findById(req.body.id, 'slug', function(err, slugTitle) {
if(err) {
console.log(err);
}
fs.unlink("path/"+slugTitle+".md", function(err) {
if(err) {
console.log(err);
} else {
console.log("Deleted the old markdown file: " + slugTitle +".md");
}
});
});
You may want to look into using a database system like MongoDB or SQL to do this instead. It's usually easier to use a database instead of writing all this stuff yourself. No need to reinvent the wheel, so to speak. It looks like you're already using one to store the meta-data, why not do so for the entire article?
That being said, yes it would seem that your initial code snippet should work.

Categories

Resources