Angular: Push Generated Timestamp on Submitted Form - json

I've written a form in Angular that sends submitted data in my form to an object called places in my Firebase.
HTML
<form role="form" name="addPlaceForm" ng-submit="createHospital(newHospital)">
<input type="text" placeholder="Enter title here" ng-model="newHospital.title">
<button type="submit" class="btn btn-primary btn-lg">Submit</button>
</form>
JS
var rootRef = new Firebase('URL');
var placesRef = rootRef.child('places');
function createHospital(hospital) {
placesRef.push(hospital);
}
Is there a way I can push a generated timestamp called created_at to my places object when it's submitted?
"created_at" : "2014-07-15T01:52:33Z"
And what about other automated data, like pushing a unique ID, for example.
Any help with this would be appreciated. Thanks in advance!

Is there a way I can push a generated timestamp called created_at to my places object when it's submitted?
An alternative to passing the timestamp from the client is to use Firebase's built-in Firebase.ServerValue.TIMESTAMP, which is documented as:
A placeholder value for auto-populating the current timestamp (time since the Unix epoch, in milliseconds) by the Firebase servers.
So you could do something like this:
function createHospital(hospital) {
hospital.created_at = Firebase.ServerValue.TIMESTAMP;
placesRef.push(hospital);
}
See this post for more information:https://www.firebase.com/blog/2013-06-17-howto-build-a-presence-system.html
What about other automated data, like pushing a unique ID?
When you call the Firebase push method a unique ID is already generated for you. The documentation for push:
Generates a new child location using a unique name and returns a Firebase reference to it.
This ID is guaranteed by Firebase to be unique, specifically so that your application doesn't have to worry about it. The push-generated ID takes a form like -JXd1pbUU89Xbd4BYvx6, -JZoLcBKnd1A8Gn-ZP0I, etc.
I would recommend sticking to that ID, instead of generating your own additional ID. If you prefer to to generate your own IDs, I would solely use that ID and use it to name your node instead of letting push generate one for you:
var newID = ID_GENERATE_FUNCTION();
placesRef.child(newID).set(hospital);
Note that here too I don't store the newID in the hospital object.

Right when you add the hospital to the array you can create the two parameters you want:
function createHospital(hospital) {
var newHospital = angular.copy(hospital);
newHospital.created_at = new Date();
newHospital.ID = ID_GENERATE_FUNCTION();
placesRef.push(newHospital);
}

Related

Create JSON object from Dynamic NgModel

I have a service which returns a JSON of type array[obj1{name, usage, id}, obj2{name, usage, id}] on HTML page I am creating a form with form field = name and it is pre-populated with value = usage. Ex: if there are 2 objects inside array where name1=a usage1=1 and name2=b and usage2=2, 2 form fields will be created. Form field names will be name1 and name2 and will be filled already with usage1 and usage2 value respectively. I am doing this with this code:
<form>
<div class="form-row">
<div class="form-group" *ngFor="let item of items">
<label>{{item.name}}</label>
<input type="number" min="0" [id]="item.name" [name]="item.name" class="form-control" [(ngModel)]="item.usage">
</div>
</div>
</form>
It is working fine. Now suppose user changes the value for usage1 and usage2. On submit button I have to create a json object in typescript and send it in the API. I am facing issues to create the JSON object. I have tried:
onSubmit{
this.changedValues = this.items.usage;
console.log(this.changedValues);
}
But console.log return undefined. Json object I am expecting should be something of they type:
changedValues[{upadatedUsage1, id1},{updatedUsage2, id2}]
How can I create a json object dynamically and also how can I send the correct id with the correct updated usage value. Thank you
The reason for undefined value is that, items is an array and hence doesn't have the property usage
onSubmit {
this.changedValues = this.items;
console.log(this.changedValues);
}
This should give the array with updated values.

Laravel, delete a queue job by user id

Each time a user is created or updated, an email will be send when some timestamp is reached.
I control this by queues. Each queue is stored in the "jobs" table.
That table has a column called "payload" which is a json with all the info of that job. In my case, a payload of this is like this one:
{
"job":"Illuminate\\Queue\\CallQueuedHandler#call",
"data":{
"commandName":"Illuminate\\Mail\\SendQueuedMailable",
"command":"O:34:\"Illuminate\\Mail\\SendQueuedMailable\":1:{s:11:\"\u0000*\u0000mailable\";O:16:\"App\\Mail\\Expired\":16:{s:7:\"\u0000*\u0000user\";O:45:\"Illuminate\\Contracts\\Database\\ModelIdentifier\":2:{s:5:\"class\";s:8:\"App\\User\";s:2:\"id\";i:1020;}s:4:\"from\";a:0:{}s:2:\"to\";a:1:{i:0;a:2:{s:7:\"address\";s:24:\" example#gmail.com\"\";s:4:\"name\";N;}}s:2:\"cc\";a:0:{}s:3:\"bcc\";a:0:{}s:7:\"replyTo\";a:0:{}s:7:\"subject\";N;s:4:\"view\";N;s:8:\"textView\";N;s:8:\"viewData\";a:0:{}s:11:\"attachments\";a:0:{}s:14:\"rawAttachments\";a:0:{}s:9:\"callbacks\";a:0:{}s:10:\"connection\";N;s:5:\"queue\";N;s:5:\"delay\";N;}}"
}
}
As you can see, there job is associated with: App\\User\";s:2:\"id\";i:1020
How could I remove that job from the table, by that user id? I could get all the data with DB::table('jobs) and loop until I found the id inside payload and delete it, but is there any helper or function of Laravel to do that?
You can json_decode the payload and unserialize the $payload['data']['command']
$job = DB::table('jobs')->whereId($id)->first();
$payload = json_decode($job->payload);
$mailable = unserialize($payload['data']['command']);
if ($mailable->user->id != GOOD)
DB::table('jobs')->whereId($id)->delete();
hope this helps

Updating Data within a unique randomly generated ID/KEY in firebase using HTML

function updateFirebase(){
const fb=firebase.database().ref()
//get field values
author = document.getElementById('uname').value
user_email = document.getElementById('umail').value
data = {author, user_email}
//update database
fb.child('Article/').update(data);
}
</script>
I have problem with my code. I want to update the data inside a table named "Article". Article has generated items with a unique key/id and each key has its own content. Lets say I want to be able to edit the "author" or change the "title", the problem is they each have a randomly generated key/id that I cant access. for example that "-LS39kReBHrKGqNj7h_". I can only save the data inside the "Article" tree but I cant change the "author" or the "title". How do i get a workaround this so I can change those properties?
Here is how my firebase looks like
It depends whether you have the record reference on the frontend before update or not (whether you have fetched it before you are trying to update it).
But generally, you have two options
You can store the key reference as an "id" field on the object.
To achieve that, you need two step process when creating the record at the first place
// Creates a new record in DB and returns it to you. Now you can get the "key"
const newRecord = firebase.database().ref('TABLE_NAME_REF').push();
newRecord.set({
id: newRecord.key
...
});
This is great if you fetch the list of records on the frontend and then you want to update one of them. Then you can just build the ref path like this
fb.child('Article/' + record.id ).update(data); // where record is the prefetched thing
You need to find the element based on its fields first. And once you have it, you can update it right away.
To achieve this, you can simply do something like:
firebase.database()
.ref('TABLE_NAME_REF') // let's say 'Article'
.orderByChild('RECORD_KEY') // Let's say 'author'
.equalTo('KEY_VALUE') // let's say 'zoranm'
.limitToFirst(1)
.once("value")
.then(res => {
// You need to loop, it always returns an array
res.forEach(record => {
console.log(record.key); // Here you get access to the "key"
fb.child('Article/' + record.key ).update(data); // This is your code pasted here
})
})

Make dynamic name text field in Postman

I'm using Postman to make REST API calls to a server. I want to make the name field dynamic so I can run the request with a unique name every time.
{
"location":
{
"name": "Testuser2", // this should be unique, eg. Testuser3, Testuser4, etc
"branding_domain_id": "52f9f8e2-72b7-0029-2dfa-84729e59dfee",
"parent_id": "52f9f8e2-731f-b2e1-2dfa-e901218d03d9"
}
}
In Postman you want to use Dynamic Variables.
The JSON you post would look like this:
{
"location":
{
"name": "{{$guid}}",
"branding_domain_id": "52f9f8e2-72b7-0029-2dfa-84729e59dfee",
"parent_id": "52f9f8e2-731f-b2e1-2dfa-e901218d03d9"
}
}
Note that this will give you a GUID (you also have the option to use ints or timestamps) and I'm not currently aware of a way to inject strings (say, from a test file or a data generation utility).
In Postman you can pass random integer which ranges from 0 to 1000, in your data you can use it as
{
"location":
{
"name": "Testuser{{$randomInt}}",
"branding_domain_id": "52f9f8e2-72b7-0029-2dfa-84729e59dfee",
"parent_id": "52f9f8e2-731f-b2e1-2dfa-e901218d03d9"
}
}
Just my 5 cents to this matter. When using randomInt there is always a chance that the number might eventually be present in the DB which can cause issues.
Solution (for me at least) is to use $timestamp instead.
Example:
{
"username": "test{{$timestamp}}",
"password": "test"
}
For anyone who's about to downvote me this post was made before the discussion in comments with the OP (see below). I'm leaving it in place so the comment from the OP which eventually described what he needs isn't removed from the question.
From what I understand you're looking for, here's a basic solution. It's assuming that:
you're developing some kind of script where you need test data
the name field should be unique each time it's run
If your question was more specific then I'd be able to give you a more specific answer, but this is the best I can do from what's there right now.
var counter = location.hash ? parseInt(location.hash.slice(1)) : 1; // get a unique counter from the URL
var unique_name = 'Testuser' + counter; // create a unique name
location.hash = ++counter; // increase the counter by 1
You can forcibly change the counter by looking in the address bar and changing the URL from ending in #1 to #5, etc.
You can then use the variable name when you build your object:
var location = {
name: unique_name,
branding_domain_id: 'however-you-currently-get-it',
parent_id: 'however-you-currently-get-it'
};
Add the below text in pre-req:
var myUUID = require('uuid').v4();
pm.environment.set('myUUID', myUUID);
and use the myUUID wherever you want
like
name: "{{myUUID}}"
It will generate a random unique GUID for every request
var uuid = require('uuid');
pm.globals.set('unique_name', 'testuser' + uuid.v4());
add above code to the pre-request tab.
this was you can reuse the unique name for subsequent api calls.
Dynamic variable like randomInt, or guid is dynamic ie : you donot know what was send in the request. there is no way to refer it again, unless it is send back in response. even if you store it in a variable,it will still be dynamic
another way is :
var allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var shuffled_unique_str = allowed.split('').sort(function(){return 0.5-Math.random()}).join('');
courtsey refer this link for more options

Can two parameters with the same name be passed to a service?

I'm passing parameters to a server from a Flash Builder application. I want to search both for "teachers" and for "rooms". I can do this via an HTML page, as follows:
<input type="checkbox" name="searchFor" value="teachers" />teachers
<input type="checkbox" name="searchFor" value="rooms" />rooms
So there are two inputs, both named searchFor. When submitted, the request looks like this:
searchFor: teachers
searchFor: rooms
In other words, two parameters are passed.
I'm trying to do the same thing in Flash Builder using an object called param:
param.query = pQuery;
param.searchFor = "teachers";
param.searchFor = "rooms";
searchUsersService(param);
Flex overwrites the one with the other, as I suspected it would, so all that is submitted is "rooms". Is it possible to pass two parameters with the same name? (or do I need to ask the server guys to rename their search parameters?)
Thanks.
You can't. It will only override the previous value:
param.query = pQuery;
param.searchFor = "teachers";
param.searchFor = "rooms"; //Will obviously override the previous value
searchUsersService(param);
What you can do is:
param.searchFor = [ "teachers", "rooms" ];
Or
param.searchFor = new ArrayCollection();
param.searchFor.add( "teachers" );
param.searchFor.add( "rooms" );
And then in the server side you can get all the values from your array.