moleculer-db
moleculer-db copied to clipboard
The Sequelize adapter doesn't seem to work when you use the base structure specified on the docs.
The examples provided on the docs regarding the Sequelize adapter implementation maybe don't take into count the probability that somebody may be using Moler Runner to execute its code. The following example can be found in the readme of the project:
const { ServiceBroker } = require("moleculer");
const DbService = require("moleculer-db");
const SqlAdapter = require("moleculer-db-adapter-sequelize");
const Sequelize = require("sequelize");
const broker = new ServiceBroker();
// Create a Sequelize service for `post` entities
broker.createService({
name: "posts",
mixins: [DbService],
adapter: new SqlAdapter("sqlite://:memory:"),
model: {
name: "post",
define: {
title: Sequelize.STRING,
content: Sequelize.TEXT,
votes: Sequelize.INTEGER,
author: Sequelize.INTEGER,
status: Sequelize.BOOLEAN
},
options: {
// Options from http://docs.sequelizejs.com/manual/tutorial/models-definition.html
}
},
});
broker.start()
// Create a new post
.then(() => broker.call("posts.create", {
title: "My first post",
content: "Lorem ipsum...",
votes: 0
}))
// Get all posts
.then(() => broker.call("posts.find").then(console.log));
Everything seems to be alright, but if you try to execute code based on such an example, you'll get the following error: Service name can't be empty! Maybe it is not a valid Service schema. Maybe is it not a service schema?.
Based on what I've read on similar issues, the error comes out when you run your code through Molecular Runner since it doesn't require you to start brokers in service files. If you want to get over the problem, you just have to rewrite the service as follows and everything should work as expected:
const { ServiceBroker } = require("moleculer");
const DbService = require("moleculer-db");
const SqlAdapter = require("moleculer-db-adapter-sequelize");
const Sequelize = require("sequelize");
//Generating a new Service.
module.exports = {
name: "posts",
mixins: [DbService],
adapter: new SqlAdapter("sqlite://:memory:"),
model: {
name: "post",
define: {
title: Sequelize.STRING,
content: Sequelize.TEXT,
votes: Sequelize.INTEGER,
status: Sequelize.BOOLEAN
},
options: {}
},
settings: ["id", "title", "content", "votes", "status"],
};
A little explanatory note under (or over) the examples regarding the Sequelize adapter could be really useful, since it may save a lot of debugging time.