@@ -19,36 +19,40 @@ class Posts {
1919 }
2020
2121 async add ( title , text , authors ) {
22- // This is unsafe! This is for demo purposes only, you should use parameterized queries.
2322 const articleRes = await this . db . query (
24- `INSERT INTO posts (title, text) VALUES ('${ title } ', '${ text } ') RETURNING id;`
23+ 'INSERT INTO posts (title, text) VALUES ($1, $2) RETURNING id' ,
24+ [ title , text ]
2525 ) ;
2626
2727 const articleId = articleRes . rows [ 0 ] . id ;
2828
2929 for ( const author of authors ) {
3030 const authorExists = await this . db . query (
31- `SELECT id FROM authors WHERE name = '${ author } ';`
31+ 'SELECT id FROM authors WHERE name = $1' ,
32+ [ author ]
3233 ) ;
3334 let authorId ;
3435 if ( authorExists . rows . length === 0 ) {
3536 const authorRes = await this . db . query (
36- `INSERT INTO authors (name) VALUES ('${ author } ') RETURNING id;`
37+ 'INSERT INTO authors (name) VALUES ($1) RETURNING id' ,
38+ [ author ]
3739 ) ;
3840 authorId = authorRes . rows [ 0 ] . id ;
3941 } else {
4042 authorId = authorExists . rows [ 0 ] . id ;
4143 }
4244
4345 await this . db . query (
44- `INSERT INTO post_authors (post_id, author_id) VALUES (${ articleId } , ${ authorId } );`
46+ 'INSERT INTO post_authors (post_id, author_id) VALUES ($1, $2)' ,
47+ [ articleId , authorId ]
4548 ) ;
4649 }
4750 }
4851
4952 async find ( title ) {
5053 const post = await this . db . query (
51- `SELECT title, text FROM posts WHERE title = '${ title } ';`
54+ 'SELECT title, text FROM posts WHERE title = $1' ,
55+ [ title ]
5256 ) ;
5357
5458 return post . rows . length > 0 ? post . rows [ 0 ] : null ;
0 commit comments