I have been following a tutorial. In the resolvers, specifically in user.ts, I cannot understand the user = result.raw[0] line of code. I did understand the logic prior to it. Can someone please help me understand what actually happens here?
let user;
try {
// User.create({}).save()
const result = await getConnection()
.createQueryBuilder()
.insert()
.into(User)
.values({
username: options.username,
email: options.email,
password: hashedPassword,
})
.returning("*")
.execute();
user = result.raw[0];
user = result.raw[0];
CodePudding user response:
In ECMAScript, there are two ways to access a property of an object:
obj.identifier
obj[expression]
The main difference between the two ways is how you are allowed to specify the property. If you use the obj.identifier
syntax, then you can only use valid ECMAScript identifiers. You would not be able to access a property named 0
this way, for example. Also, the identifier
will always be interpreted as a string, there is no way to access Symbol
-keyed properties this way.
If you use the obj[expression]
syntax, then the expression
can be any, well, expression. Particularly, any expression that evaluates to a string, a number, or a Symbol
.
So, the line
result.raw[0]
simply means "get the property named "raw"
of the object that is referenced by the variable result
, then get the property named "0"
of that object.
CodePudding user response:
Actually result.raw[0]
pointed to the first record inserted in the table.
If add record like below in a table:
-- create table (
-- id serial,
-- username varchar(30),
-- password varchar(200),
-- email varchar(100)
-- );
insert into user (username, password, email) values
('user1', 'my-password', '[email protected]')
returning *;
Output has something like that:
id | username | password | |
---|---|---|---|
1 | user1 | my-password | [email protected] |
The above data (data was insert and after that) has been returned from database and store in result.raw[0]