Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 7 years ago.
Improve this question
Can any one please show me a concrete working example of transformWrite. At the moment I've got this example which I am not sure how to plug into my code: https://github.com/CollectionFS/Meteor-CollectionFS#transformwrite--transformread
My attempt code is as below. Please show me how to make it work.
FS.Utility.eachFile(event, function(file) {
file = transformWrite: function(fileObj, readStream, writeStream) {
readStream.pipe(writeStream);
}
Images.insert(file, function (err, fileObj) {
// Inserted new doc with ID fileObj._id, and kicked off the data upload using HTTP
});
});
You need to define the transform on the store, not during insert. Here is how I do it on step3d.com (a simple 3D CAD-file viewer):
transformServer = function(fileObj, readStream, writeStream) {
if (fileObj.extension() == "stl") {
readStream.pipe(writeStream); // can handle as is
} else if (fileObj.extension() == "step"
|| fileObj.extension() == "stp") {
step2stl(fileObj, readStream, writeStream); // convert from step to stl format
} else {
console.log("no idea how to handle", fileObj.extension());
readStream.pipe(writeStream);
}
};
var store = new FS.Store.GridFS("files", {
transformWrite: function(fileObj, readStream, writeStream) {
transformServer(fileObj, readStream, writeStream);
}
});
Files = new FS.Collection("files", {
stores: [store]
});
Afterwards, any insertion into the Files collection will be transformed before storing the file in the database.
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 days ago.
Improve this question
I am working on an application which enables logged in users to perform certain calls to my backend API. These API endpoints often call other APIs, such as Google's Geocoding API, as in the example below. As anyone is free to create an account on my application, I'm wondering what the best ways to prevent them from being abused or spammed is?
Here is an example of one of my NextJS backend endpoints:
export default async function handler(req, res) {
const { userId } = getAuth(req);
if (!userId) {
return res.status(401).json({
data: null,
error: "User is not logged in"
});
};
if (req.method === 'POST') {
try {
const client = new Client({});
client
.geocode({
params: {
address: req.body.postCode,
key: {process.env.GOOGLE_MAPS_API_KEY},
outputFormat: "json",
language: "en",
region: "gb"
},
timeout: 1000, // milliseconds
})
.then((r) => {
res.status(200).json(r.data.results[0]);
})
.catch((err) => {
console.log(e.response.data.error_message);
});
} catch (err) {
res.status(err.statusCode || 500).json(err.message);
}
} else {
res.setHeader('Allow', 'POST');
res.status(405).end('Method Not Allowed');
}
};
A logged in user would currently be able to repeatedly trigger this endpoint - which would essentially provide unlimited access to Google's Geocoding API.
I have already restricted my API keys so that they can only be triggered via requests on my website and for specific Google APIs. However, this does not cover a malicious user creating an account and hitting the endpoints whilst authenticated.
I'm struggling to find any documentation which provides a best practice approach for this, so any advice would be really helpful.
Thanks!
i've to edit a web application already existing that i don't know at all.
into a web page this code create an unique number:
Fingerprint2.get(function (components) {
try {
var values = components.map(function (component) { return component.value });
var murmur = Fingerprint2.x64hash128(values.join(''), 31);
$("#id-fingerprint").val(murmur);
} catch (err) {
}
});
our customers are working on cloned pc, same hardware and software, so it happens two different users generate the same unique number.
my purpose is to add username to existing code.
is this a good way to do it?
Fingerprint2.get(function (components) {
try {
var values = components.map(function (component) { return component.value });
var username = $("#username").val();
values.push(username);
var murmur = Fingerprint2.x64hash128(values.join(''), 31);
$("#id-fingerprint").val(murmur);
} catch (err) {
}
});
You can add a custom component, you can learn more in the Extending FingerprintJS guidelines. Simply put, you just need to add your id into the components object.
const result = await fp.get()
const components = {
...result.components,
foo: username
}
const visitorId = FingerprintJS.hashComponents(components)
I'm writing Quiz app of sorts using VueJS and Firebase firestore.
So far I've made everything except this one last part.
Users are allowed to answer questions without being logged in.
And at the final stage, there is one last question. Everyone can answer this question, but I need to be able to detect who is first.
So far I've tried with checking if answers collection is empty, this works, but response time is the issue and I can reproduce easily two or more users answering at the same time and having message they are the winners.
I'm currently trying with transactions, but cannot figure it out how to catch if document already exists. Here's the sample code:
let vm = this;
fsdb.runTransaction(function (transaction) {
let voteDocRef = fsdb.collection('final_vote').doc('vote');
return transaction.get(voteDocRef).then(function (voteDoc) {
if (!voteDoc.exists) {
voteDocRef.set({voted: true}).then(function () {
vm.trueAnswer(index);
return 'set executed!';
}).catch(function () {
vm.falseAnswer(index);
throw 'Someone already voted!';
});
return 'Document created!';
} else {
throw 'Someone already voted!';
}
});
vm.trueAnswer and vm.falseAnswer are the methods I'm using to show the popup message.
And this is the method that's triggered once the user submits the answer.
At first I've tried with rules that everyone can read, write ... but now I'm trying to limit write only if document doesn't exist. Here's the current rule set:
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
match /{collectionName}/{docId} {
allow create: if collectionName == 'final_vote' && docId == 'vote';
}
}
}
So far this doesn't work as expected.
Any ideas on how to approach this?
Would you try the following code?
let vm = this;
fsdb.runTransaction(function (transaction) {
let voteDocRef = fsdb.collection('final_vote').doc('vote');
return transaction.get(voteDocRef).then(function (voteDoc) {
if (voteDoc.data().voted !== true) {
voteDocRef.set({voted: true}).then(function () {
vm.trueAnswer(index);
return 'set executed!';
}).catch(function () {
vm.falseAnswer(index);
throw 'Someone already voted!';
});
return 'Document created!';
} else {
throw 'Someone already voted!';
}
});
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
allow read, write: if false;
}
match /final_vote/{docId} {
allow create, update: if true;
}
}
}
I think that final_votes is better than final_vote as collection name.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
Good Day,
I am trying to build a very small display application for a database. The application will need to display data dynamically from a connected database without the user refreshing constantly but the user needs to have a sync rate < 5 sec. I have looked into a web API and MVC structures (CRUD). Which work great for a single user input but I need the display to change based on any changes made by any user to the database. The application will only have a small amount of users (<20) and due to our connection, the lighter the application is the better. A web application would be ideal so that the client-side is display and input only.
I was hoping to get some feedback as to which technology to start to look at for the front end. I have built the database with Entity Framework.
Any input would be appreciated.
Regards,
Peter
WebSockets
The very best solution is to use WebSockets. WebSockets consist an advanced technology, which creates a duplex connection between the client and the server and whenever the server needs to be sending data, it can send it to active connections. Since you are using ASP.NET, SignalR would be very helpful for you. You can watch very good videos about SignalR.
Push Notifications
You can also use push notifications to listeners to push. The Push API would help you in this. This is not as good as WebSockets, since the client will have to work with HTTP requests if it was to send requests to the server.
Polling
You can create your own API function at the server and use polling to send requests to it. An example for a general-purpose poller is this one:
function Initializable(params) {
this.initialize = function(key, def, private) {
if (def !== undefined) {
(!!private ? params : this)[key] = (params[key] !== undefined) ? params[key] : def;
}
};
}
function Poller(params) {
Initializable.call(this, params);
var that = this;
this.initialize("url", window.location.href);
this.initialize("interval", 5000);
this.initialize("type", "POST");
this.initialize("method", "POST");
this.initialize("data", {});
this.initialize("strict", true);
this.initialize("isWebSocket", false);
this.initialize("message", "Poll");
this.initialize("webSocketHandler", undefined);
if (this.isWebSocket && !this.webSocketHandler) {
this.initialize("module", module);
this.initialize("page", page);
this.webSocketHandler = new WebSocketHandler({
ConnectNow: true,
module: this.module,
page: this.page,
message: this.message,
Message: function(e) {
that.done(e.data);
}
});
}
var defaultFunction = function() {};
this.initialize("done", defaultFunction);
this.initialize("fail", defaultFunction);
this.initialize("always", defaultFunction);
//WS
this.initialize("isWebSocketPrepared", function() {
return true;
});
this.initialize("sendingWebSocket", function() {});
this.initialize("handleUnpreparedWebSocket", function() {});
this.initialize("sendWSData", function(message) {
if (that.webSocketHandler.isReady()) {
if (that.isWebSocketPrepared()) {
that.webSocketHandler.send(JSON.stringify({
module: module,
page: page,
message: message
}));
that.sendingWebSocket();
} else {
that.handleUnpreparedWebSocket();
}
} else {
that.handleUnpreparedWebSocket();
}
});
this.isRunning = function() {
return !!params.intervalID;
};
this.run = function() {
if (this.strict && (this.green === false)) {
return;
}
this.green = false;
if (!that.isWebSocket) {
$.ajax({
url: this.url,
method: this.method,
data: this.data
}).done(function(data, textStatus, jqXHR) {
that.green = true;
that.done(data, textStatus, jqXHR);
}).fail(function(jqXHR, textStatus, errorThrown) {
that.green = true;
that.fail(jqXHR, textStatus, errorThrown);
}).always(function(param1, param2, param3) {
that.green = true;
that.always(param1, param2, param3);
});
} else {
that.sendWSData(that.message);
}
};
this.start = function() {
if (!params.intervalID) {
this.run();
params.intervalID = setInterval(this.run.bind(this), this.interval);
}
};
this.stop = function() {
if (!!params.intervalID) {
clearInterval(params.intervalID);
params.intervalID = undefined;
}
};
}
Forever Frame
You can also use forever frames, which are iframes which are loading forever. Read more here: https://vinaytech.wordpress.com/2008/09/25/long-polling-vs-forever-frame/
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I have a Firestore document representing a day with a subcollection containing reservations for this day in a Firestore database.
Here is JSON example of my data structure:
{
"Day":{
"ReservationsCount":2,
"Reservations":[
{
"Order":1
},
{
"Order":2
}
]
}
}
I need to add a set of documents, set their ordinal number in collection and update the ReservationsCount in one transaction.
I tried to use firestore transactions and batched writes, but as far I understand, they do not support adding document to a collection in transaction (according to documentation only combination of set(), update(), or delete() operations).
I tried to do update the values using cloud functions, but they are in beta and there are known issues with performance and reliability, so I got sometimes wrong results.
Is there any way to update existing document and add documents to its subcollection within one transaction?
The following should do the trick. You have to pass to the updateRes() function the ref of the 'day" doc, the ref of the sub-collection and an array containing an object for each document to add to the sub-collection.
Just open the HTML file in a browser.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://www.gstatic.com/firebasejs/5.0.4/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/5.0.4/firebase-firestore.js"></script>
</head>
<body>
<script>
var config = {
apiKey: "...",
authDomain: "...",
databaseURL: "...",
....
};
firebase.initializeApp(config);
var firestoredb = firebase.firestore();
function updateRes(dayDocRef, orderCollectionRef, refAndDataArray) {
return firestoredb.runTransaction(function (transaction) {
return transaction.get(dayDocRef)
.then(function (dayDoc) {
if (!dayDoc.exists) {
throw "Document Day does not exist!";
}
newResCount = dayDoc.data().ReservationsCount + refAndDataArray.length;
return transaction.update(dayDocRef, { ReservationsCount: newResCount });
})
.then(function () {
var t = transaction;
refAndDataArray.forEach(function (element) {
t = t.set(orderCollectionRef.doc(element.ref), element.data);
});
return t;
});
}).then(function () {
console.log("Transaction successfully committed!");
}).catch(function (error) {
console.log("Transaction failed: ", error);
});
};
var dayDocRef = firestoredb.collection("Days").doc("Day");
var orderCollectionRef = dayDocRef.collection("Reservations"); //The sub-collection is called "Reservations"
var refAndDataArray = [{ ref: "3", data: { Order: 3, otherData: "foo" } }, { ref: "4", data: { Order: 4, otherData: "bar" } }];
updateRes(dayDocRef, orderCollectionRef, refAndDataArray);
</script>
</body>
</html>