PhilWaldmann / openrecord

Make ORMs great again!
https://openrecord.js.org
MIT License
486 stars 38 forks source link

TypeError: User.create is not a function #77

Closed rottenoats closed 5 years ago

rottenoats commented 5 years ago

OpenRecord Version: ^2.7.2 Node: v11.1.0 npm: 6.4.1

I'm getting an error when I do the following:

await User.create(req.body.data)

When I log User I get this:[Function: User]

//config/database/openRecord.js
/** more code above */
let store = new Store({
    database, 
    user, 
    password, 
    host,
    autoConnect: true,
    autoAttributes: true,
    models: require("../../app/models/models")
}); 
//app/models/models.js
module.exports = [
    require("./user")
]
//app/models/user.js
const Store = require('openrecord/store/mysql');

class User extends Store.BaseModel {
    static definition(){
        this.validatePresenceOf(
            'first_name', 'last_name', 'email', 'password'
        );

        this.validatesConfirmationOf('password');
        this.validateFormatOf('email', 'email');
    }

    fullName(){
        return `${this.first_name} ${this.last_name}`
    }
}

module.exports = User;

What am I doing wrong ?

PhilWaldmann commented 5 years ago

Hi @rottenoats

two small typos are validatePresenceOf (should be validatesPresenceOf) and validateFormatOf (should be validatesFormatOf).

However, this is not the error you experience! I'm pretty sure that you forget to wait until the store is ready. A simple await store.ready() before your User.create should solve your problem.
A better place would be before starting your webserver. (e.g. before server.listen() for express)

rottenoats commented 5 years ago

@PhilWaldmann thanks for the quick response.

I see where the problem is coming from. So you're recommending I wrap the creation of my webserver in the store.ready() function?

Also would be nice if this was mentioned in the documentation (unless I read too quickly).

https://openrecord.js.org/#/modify?id=createdata

The only examples of when store.ready() is used is for queries.

PhilWaldmann commented 5 years ago

Thanks for the feedback. I'll make it more clear in the docs!

If you use express (but it's similar with other frameworks) I would do the following:

const express = require('express')
const store = require('./store')

const app = express()

async function start() {
  // add middleware ...

  await store.ready()

  // start express server
  app.listen()
}
start()

For usage in serverless (or similar frameworks):

// set autoConnect to false
const store = require('./store')

module.handler = await function(event, context, callback){
  store.connect()
  await store.ready()
  // your business logic here
  store.close()
  callback(null, result)
}
rottenoats commented 5 years ago

@PhilWaldmann thanks for the example, much appreciated. If you have a SO profile you can leave an answer on my SO question if you like.

PhilWaldmann commented 5 years ago

sure ;)