Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Node.jsのライブラリ周りでハマった話

KSK
June 29, 2018
650

 Node.jsのライブラリ周りでハマった話

主にSequelizeのScopeの話

KSK

June 29, 2018
Tweet

More Decks by KSK

Transcript

  1. Sequelize ɾNode.js ༻ͷOR Mapper ɹ- http://docs.sequelizejs.com/ ɹ- Rails Ͱ͍͏Active Record

    ɾҰ൪ϝδϟʔͰ΍Γ͍ͨ͜ͱ͸Ͱ͖ͦ͏ ɾݹ͍৘ใ΋ώοτ͢ΔͷͰ஫ҙ (ver 3.x) ɹ- ࠷৽͸ ver 4.38 ͱ ver 5 Beta (2018/06/24)
  2. ɾshiftSec ͕࣌ࠁͷࠩ෼ ͜Μͳײ͡Ͱwrapͨ͠ import moment from 'moment-timezone' import shiftSec from

    '../config/timeShift' if (process.env.NODE_ENV !== 'production') { moment.now = () => { return new Date().getTime() + shiftSec * 1000 } } export default moment
  3. ɾ$lte ͸ ” ≦ ”ʢLess Than or Equalʣ Scope const

    now = moment() const Card = sequelize.define('card', { // Attributes }, { scopes: { released: { where: { releasedAt: { $lte: now }, }, }, }, }) Card.scope(‘releasedAt').findAll() // ϦϦʔεޙͷΧʔυͷΈ
  4. defaultScope ɾ໌ࣔతʹॲཧ͠ͳ͚Ε͹ࣗಈͰద༻ const Card = sequelize.define('card', { // Attributes },

    { defaultScope: { where: { isActive: true, }, }, }) Card.findAll() // scope ͷࢦఆͳ͠Ͱ acitve ͷΈ
  5. ͜Μͳײ͡ ʢ࣌ؒ଍Βͣݕূෆे෼Ͱ͢ɻɻɻʣ class User < ApplicationRecord has_many :friends end class

    Friend < ApplicationRecord belongs_to :user default_scope -> { where(is_goodlooking: true) } end User.first.friends # ͨͩ͠ΠέϝϯʹݶΔ User.first.friends.unscoped # “.first” ͷߜΓࠐΈ͕ແࢹ͞ΕΔ Friend.new # <id:nil, is_goodlooking:true … > ࠷ॳ͔ΒΠέϝϯ
  6. ҙ֎ͱେৎ෉ͬΆ͍͔…ʁ ɾunscope ͱ default஋ͷ໰୊͸ΫϦΞ // ϢʔβͷߜΓࠐΈ͸ޮ͍ͨ·· const firstUser = await

    User.findOne() firstUser.findAll({ include: [{ model: Friend.unscoped() }], }) const newFriend = Friend.build() // { id: null }
  7. ݁ہͲ͏ͳͷʁ ɾ஌Β͵ؒʹϑΟϧλϦϯά͞ΕΔɺͱ͍͏ ɹέʔε͸ग़ͯ͘Δ ɹ- ΍͸Γཚ༻͸ݫېʂʂ❌ ɹ- ࢖͏ͱͨ͠ΒɺϦϦʔε࣌ࠁ·Ͱຊ൪؀ڥʹ ɹ ઈରग़ͪ͠Ό͍͚ͳ͍෺ʹ Soft

    Delete తʹ ʢ- Soft Delete ࣗମͷੋඇ΋͋Δʣ ɾ๻ͷ஌Βͳ͍᠘͕·ͩ·ͩ͋Γͦ͏ͳ ɹؾ΋͢ΔͷͰੋඇڭ͍͑ͯͩ͘͞…$