I am very new to nodejs and typescript.
I have try to provide an API via express.
I have try to return a custom object on my API who looks like that :
export class Auction {
private _currentPrice:number = 0;
private _auctionName:string;
public constructor(currentPrice: number , auctionName: string) {
this._currentPrice = currentPrice;
this._auctionName = auctionName;
}
/**
* Getter auctionName
* #return {string}
*/
public get auctionName(): string {
return this._auctionName;
}
/**
* Setter auctionName
* #param {string} value
*/
public set auctionName(value: string) {
this._auctionName = value;
}
/**
* Setter currentPrice
* #param {number } value
*/
public set currentPrice(value: number ) {
this._currentPrice = value;
}
/**
* Getter currentPrice
* #return {number }
*/
public get currentPrice(): number {
return this._currentPrice;
}
}
But what I have seen is that the answer of my API is something like :
{"_currentPrice":0,"_auctionName":"toto"}
I was expecting something like
{"currentPrice":0,"auctionName":"toto"}
Is there any way to automaticaly convert it to the format I want ?
This is happening because when the TypeScript is compiled to JavaScript, objects created by that class have public _currentPrice and _auctionName properties (because TypeScript "private" properties are only private in terms of TypeScript's type system) and they don't have their own currentPrice and auctionName properties (they inherit them from their prototype, which has them as accessor properties). JSON.stringify only includes "own" properties.
You can deal with it in a few ways:
By using simple properties for currentPrice and auctionName. You have public accessors for both get and set for both properties, so there doesn't seem to be any reason to use private properties to hold their values. Or,
By providing your own toJSON method for the class:
toJSON() {
return {currentPrice: this._currentPrice, auctionName: this._auctionName};
}
Despite the name "toJSON", this method isn't supposed to return JSON; it's supposed to return the value for the object that should be converted to JSON. So in this case, you return an object with the properties you want the returned JSON to have.
A third solution would be to use JavaScript's own private properties (they're supported in up-to-date Node.js versions) and "own" accessors for them on the objects, but I don't think TypeScript supports JavaScript's private properties yet.
Related
I have under_score named properties in my class like transaction_id or web_order_item_id. And I want to customize the parameter name in my setters when I generate it.
For now it generate this:
/**
* #param int $original_transaction_id .camelCase()
*/
public function setOriginalTransactionId(int $original_transaction_id): void
{
$this->original_transaction_id = $original_transaction_id;
}
But I want this:
/**
* #param int $originalTransactionId .camelCase()
*/
public function setOriginalTransactionId(int $originalTransactionId): void
{
$this->original_transaction_id = $originalTransactionId;
}
I have tried to change this behavior in Settings/Editor/File and Code Templates/Code/Php Setter Method but I couldn`t found ability to do it.
There is a variable in the template:
${NAME}
But it returned value in this form $OriginalTransactionId instead $originalTransactionId
You can try using Apache Velocity StringUtils here, like
#set($Setter_param = ${StringUtils.removeAndHump(${PARAM_NAME})})
#set($Setter_param = $Setter_param.substring(0,1).toLowerCase() + $Setter_param.substring(1))
/**
* #param ${TYPE_HINT} $${Setter_param}
*/
public ${STATIC} function set${NAME}(#if (${SCALAR_TYPE_HINT})${SCALAR_TYPE_HINT} #end$${Setter_param})#if (${VOID_RETURN_TYPE}):void #end
{
#if (${STATIC} == "static")
self::$${FIELD_NAME} = $${Setter_param};
#else
$this->${FIELD_NAME} = $${Setter_param};
#end
}
In groovy, when I want to create a property with public-read but protected-write access, I need to write the following code (as per the Groovy Docs):
class SomeClass {
/**
* Public property
*/
String someProperty
/**
* Make it protected-write
*/
protected void setSomeProperty(String someProperty) { this.someProperty = someProperty }
}
Is there a short-hand for this? Something like:
class SomeClass {
#Protected String someProperty
}
There should also be a #Private annotation along the same lines.
Note
These annotations would only affect the setter method of the property. This should allow any required access-level combination i.e.:
/** An entirely protected property */
protected String someProperty
/** An entirely private property */
private String someProperty
/** A read-only property */
final String someProperty
/** Private-Setter, Protected-Getter */
#Private protected String someProperty
There is not any shorthand way to express that, at least not in default Groovy. You could write an AST transformation which imposes rules like those you describe but Groovy does not do anything like that by default.
I hope that helps.
How can I set the default value in field.
In my document I need to set default value false for field emailnotify
In mogodb th default value should be zero.
Check my document
namespace xxx\xxxBundle\Document;
use FOS\UserBundle\Document\User as BaseUser;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* #MongoDB\Document
*/
class User extends BaseUser
{
/**
* #MongoDB\Id(strategy="auto")
*/
protected $id;
/**
* #MongoDB\Boolean
*/
protected $emailnotify;
/**
* Sets the emailnotify.
*
* #param boolean $emailnotify
*
* #return User
*/
public function setEmailnotify($emailnotify)
{
$this->emailnotify = (Boolean) $emailnotify;
return $this;
}
/**
* #return boolean
*/
public function isEmailnotify()
{
return $this->emailnotify;
}
}
I have found that setting the default value in the constructor works
public function __construct() {
$this->emailnotify = false;
}
Of course just setting the class variable to false will work for most parts if you use Doctrine to fetch the Document again afterwards, but the property will not be persisted to MongoDB like with the above.
Using Symfony2 / doctrine2, while we use the find() function to get a specific object based on the entity selected if there are relations (like OneToMany), Doctrine return all other object.
For example :
$em = $this->get(
'doctrine.orm.entity_manager',
$request->getSession()->get('entity_manager')
);
$product = $em->getRepository('MyBundle:Product')->find($id);
The result on $product will be the Product object + other linked objects like (Store, Category, ...etc.)
How can we control doctrine to determinate which object we need to be returned.
I can use Querybuilder, but i am looking if there are any function all determinate.
Doctrine return all other object
This is not how it works, at least by default.
Doctrine uses what is called lazy loading.
From the official documentation, you have the following example:
<?php
/** #Entity */
class Article
{
/** #Id #Column(type="integer") #GeneratedValue */
private $id;
/** #Column(type="string") */
private $headline;
/** #ManyToOne(targetEntity="User") */
private $author;
/** #OneToMany(targetEntity="Comment", mappedBy="article") */
private $comments;
public function __construct {
$this->comments = new ArrayCollection();
}
public function getAuthor() { return $this->author; }
public function getComments() { return $this->comments; }
}
$article = $em->find('Article', 1);
And the following explanation:
Instead of passing you back a real Author instance and a collection of
comments Doctrine will create proxy instances for you. Only if you
access these proxies for the first time they will go through the
EntityManager and load their state from the database.
Reference: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-objects.html#entity-object-graph-traversal
More information about the topic: http://www.doctrine-project.org/blog/doctrine-lazy-loading.html
You can configure extra lazy associations to avoid loading of relations in general.
/**
* #ManyToMany(targetEntity="CmsUser", mappedBy="groups", fetch="EXTRA_LAZY")
*/
protected $property;
A lot of times in a Zend Framework 2 view I'll be calling $this->escapeHtml() to make sure my data is safe. Is there a way to switch this behaviour from a blacklist to a whitelist?
PS: Read an article from Padraic Brady that suggests that automatic escaping is a bad idea. Additional thoughts?
You could write your own ViewModel class which escapes data when variables are assigned to it.
Thanks to Robs comment, I extended the ZF2 ViewModel as follows:
namespace Application\View\Model;
use Zend\View\Model\ViewModel;
use Zend\View\Helper\EscapeHtml;
class EscapeViewModel extends ViewModel
{
/**
* #var Zend\View\Helper\EscapeHtml
*/
protected $escaper = null;
/**
* Proxy to set auto-escape option
*
* #param bool $autoEscape
* #return ViewModel
*/
public function autoEscape($autoEscape = true)
{
$this->options['auto_escape'] = (bool) $autoEscape;
return $this;
}
/**
* Property overloading: get variable value;
* auto-escape if auto-escape option is set
*
* #param string $name
* #return mixed
*/
public function __get($name)
{
if (!$this->__isset($name)) {
return;
}
$variables = $this->getVariables();
if($this->getOption('auto_escape'))
return $this->getEscaper()->escape($variables[$name]);
return $variables[$name];
}
/**
* Get instance of Escaper
*
* #return Zend\View\Helper\EscapeHtml
*/
public function getEscaper()
{
if (null === $this->escaper) {
$this->escaper = new EscapeHtml;
}
return $this->escaper;
}
}
In a Controller it could be used like this:
public function fooAction()
{
return new EscapeViewModel(array(
'foo' => '<i>bar</i>'
));
//Turn off auto-escaping:
return new EscapeViewModel(array(
'foo' => '<i>bar</i>'
),['auto_escape' => false]);
}
Question:
I would appreciate it if soemebody would comment, if this is best practice or if there is a better and ecp. more efficient and resource-saving way?