[컴][nodejs] krakenjs 에서 objection ORM 사용

kraken / kraken-js / krakenjs / expressjs / express

kraken 에서 objection ORM 사용

objection 설치

npm i objection knex

코드 반영

// config/config.json
{
	...
    "database": {
        "client": "mysql",
        "connection": {
            "host": "127.0.0.1",
            "user": "myuser",
            "password": "mypw",
            "database": "mydbname",
            "charset": "utf8"
        }
    }
}
// index.ts
...
import Knex from 'knex';
import { Model } from 'objection';

var options = {
    onconfig: function (config: any, next: any) {
        const dbConfig = config.get('database')

        // Initialize knex.
        const knex = Knex(dbConfig);

        // Bind all Models to a knex instance. If you only have one database in
        // your server this is all you have to do. For multi database systems, see
        // the Model.bindKnex() method.
        Model.knex(knex);

        /*
         * Add any additional config setup or overrides here. `config` is an initialized
         * `confit` (https://github.com/krakenjs/confit/) configuration object.
         */
        next(null, config);
    }
};

const app: any = express();
app.use(kraken(options));

// models/tag.ts
import { AnyQueryBuilder, Model } from "objection";

export default class Tag extends Model {
  // https://www.typescriptlang.org/docs/handbook/2/classes.html#--strictpropertyinitialization
  // initialization 이 없이 member variable 을 넣는 typescript 문법
  id!: number 
  name!: string
  created_at!: Date
  updated_at!: Date

  static tableName = 'tag';

  static modifiers = {
    findOneOrInsert(query: AnyQueryBuilder, whereCondition: any) {
      
    },

  };

  $beforeInsert() {
    this.created_at = new Date();
  }

  $beforeUpdate() {
    this.updated_at = new Date();
  }


}

// controllers/login/index.ts
...
import Tag from "../../models/tag";

export default function _(router: any) {

    router.get('/',  async (req: any, res: any) => {

        await Tag.query().insert({
            name: 'test2-name'
          });
        
        res.send('<code><pre>' + JSON.stringify(model, null, 2) + '</pre></code>');
    });
};


mariadb client 사용

See Also

댓글 없음:

댓글 쓰기