Guest User

Untitled

a guest
Feb 18th, 2019
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.62 KB | None | 0 0
  1. const { Client } = require('pg')
  2. const fs = require('fs')
  3. const local_file = require('./your_json_data.json')
  4.  
  5.  
  6. class Postgres {
  7. constructor() {
  8. this.client = new Client({
  9. user: 'postgres',
  10. host: 'xx.xxx.xxx.xx',
  11. database: 'postgres',
  12. password: 'password',
  13. port: xxxx,
  14. })
  15.  
  16. this.client.connect()
  17. }
  18.  
  19. async query(sql) {
  20. try {
  21. const { rows } = await this.client.query(sql)
  22. return rows
  23. } catch (err) {
  24. throw err
  25. }
  26. }
  27. }
  28.  
  29. async function run() {
  30. const postgres = new Postgres()
  31.  
  32.  
  33. const makeVal = (val)=>{
  34. if(val === undefined) {
  35. return "'\"[undefined]\"'"
  36. } else {
  37. return "'" + JSON.stringify(val).replace(/'/g, "''") + "'"
  38. }
  39. }
  40.  
  41. const makeVals = (objs) => {
  42. return objs.map((obj) => makeVal(obj)).join(',')
  43. }
  44.  
  45. for(let k of Object.keys(local_file)) {
  46. try {
  47.  
  48. const query = `INSERT INTO your_table (
  49. id,
  50. title,
  51. category,
  52. author,
  53. published_at,
  54. images,
  55. )
  56. VALUES(` + makeVals([
  57. k,
  58. local_file[k].title,
  59. local_file[k].type,
  60. local_file[k].author,
  61. local_file[k].publishedAt,
  62. local_file[k].attachments.images,
  63. ]) + ')'
  64.  
  65. console.log(query)
  66. postgres.query(query)
  67. } catch(err) {
  68. throw err
  69. }
  70. }
  71. }
  72.  
  73. run()
Add Comment
Please, Sign In to add comment