Full Stack Challenge Part 3 | Seed

1 min read


oke balik lagi,, kita langsung gas aja yahhh wkwkwk.. Jadi sebelumnya kita sudah buat migrations dan berhasil,, namun dari hasil migrations berupa table belum ada data kolomnyaa., sehingga kita coba mengisi data dummy kedalamnya dengan menggunakan seeds…

{
  "name": "objection_knex",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "make-seed": "npx knex seed:make dev --knexfile ./db/knexfile.js",
    "migrate": "npx knex migrate:latest --knexfile ./db/knexfile.js",
    "script": "nodemon index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1",
    "knex": "^0.95.12",
    "objection": "^2.2.17",
    "pg": "^8.7.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.14"
  }
}

oke kita edit dulu package.json dengan menambahkan script make-seed,, setelah itu knex akan otomatis membuat file konfigurasi untuk kita pakai…

npm run make-seed

objection_knex@1.0.0 make-seed /home/laughface809/Documents/FullStack/objection_knex
npx knex seed:make dev –knexfile ./db/knexfile.js

Working directory changed to ~/Documents/FullStack/objection_knex/db

Using environment: development

Using environment: development

Using environment: development

Created seed file: /home/laughface809/Documents/FullStack/objection_knex/db/seeds/dev.js

setelah itu akan muncul file dev.js didalam folder seeds, sehingga kita bisa edit filenya menjadi ..

exports.seed = async function (knex) {
  // truncate all existing tables
  await knex.raw('TRUNCATE TABLE "user" CASCADE');
  await knex.raw('TRUNCATE TABLE channel CASCADE');
  await knex.raw('TRUNCATE TABLE post CASCADE');

  // insert seed data
  await knex('channel').insert([
    {
      id: 1,
      name: 'channel1',
    },
    {
      id: 2,
      name: 'channel2',
    },
  ]);

  await knex('user').insert([
    {
      id: 1,
      name: 'user1',
      email: 'user1@test.com',
      channelId: 1,
    },
    {
      id: 2,
      name: 'user2',
      email: 'user2@test.com',
      channelId: 2,
    },
    {
      id: 3,
      name: 'user2',
      email: 'user3@test.com',
    },
  ]);

  return knex('post').insert([
    {
      id: 1,
      title: 'post1ByUser1',
      channelId: 1,
    },
    {
      id: 2,
      title: 'post2ByUser1',
      channelId: 1,
    },
    {
      id: 3,
      title: 'post3ByUser2',
      channelId: 2,
    },
  ]);
};

oke tambahkan perintah seeds ke package.json

"seed": "npx knex seed:run --knexfile ./db/knexfile.js",

dan jalankan

npm run seed

oke jika berhasil maka kita bisa cek ke pgadmin untuk data dummynya,,, oke mungkin cukup sekian kita lanjut ke post berikut nya cyaaaa….

Bima Sena
  1. Pingback: canadian
  2. Bobbythalk says:

    Awesome thanks !!

Leave a Reply

Your email address will not be published. Required fields are marked *