Sequelize .save - undefined is not a constructor - postgresql

I am trying to save some data to a Postgres database using Sequelize. This is my code to connect to the database and create the model:
import Sequelize from 'sequelize'
const getModels = Connection => {
return {
User: Connection.define('users', {
id: { type: Sequelize.STRING, primaryKey: true },
refresh_token: { type: Sequelize.STRING }
})
}
}
const getInstance = () => {
const Connection = new Sequelize(
process.env.DATABASE_URL, {
dialect: 'postgres',
logging: process.env.NODE_ENV === 'production' ? false : console.log,
omitNull: true,
}
)
return getModels(Connection)
}
export default getInstance
I am trying to save the user id and refresh_token when the user logs in (authenticating using Auth0). Here is my code to do this:
const {User} = getInstance()
const user = User.build({ id: user_id, refresh_token: refresh_token })
user.save().then(() => {
console.log('save completed')
}).catch(error => {
console.log(`Something went wrong: ${error}`)
})
I am getting this error: Something went wrong: TypeError: undefined is not a constructor (evaluating 'new net.Stream()')
If I do console.log(user.id) or user.refresh_token I get the correct info back so the .build function is working. Something is wrong with the save function though. Thanks for any help in solving it - I am using a React app with Webpack (plus server-side rendering); I'm getting some warnings about dependencies from Webpack due to Sequelize as I'm using it on the front-end, not back-end. If anyone has any ideas on how to fix these, that'd be great:
[0] ./~/sequelize/lib/sequelize.js
[0] Critical dependencies:
[0] 686:60-73 the request of a dependency is an expression
[0] # ./~/sequelize/lib/sequelize.js 686:60-73
[0] ./~/sequelize/lib/dialects/mssql/connection-manager.js
[0] Critical dependencies:
[0] 18:15-71 the request of a dependency is an expression
[0] # ./~/sequelize/lib/dialects/mssql/connection-manager.js 18:15-71
[0] ./~/sequelize/lib/dialects/mysql/connection-manager.js
[0] Critical dependencies:
[0] 18:17-60 the request of a dependency is an expression
[0] # ./~/sequelize/lib/dialects/mysql/connection-manager.js 18:17-60
[0] ./~/sequelize/lib/dialects/postgres/connection-manager.js
[0] Critical dependencies:
[0] 20:14-57 the request of a dependency is an expression
[0] # ./~/sequelize/lib/dialects/postgres/connection-manager.js 20:14-57
[0] ./~/sequelize/lib/dialects/sqlite/connection-manager.js
[0] Critical dependencies:
[0] 22:15-71 the request of a dependency is an expression
[0] # ./~/sequelize/lib/dialects/sqlite/connection-manager.js 22:15-71
[0] webpack built 3215b07a25217c8e67e0 in 13519ms
Thanks!

Related

How to solve Vercel 500 Internal Server Error?

I have created a project that uses MongoDB to store user info and Next-Auth to authenticate users. On local host this is all working seamlessly. Previously I had a couple errors with my next-auth config, but that seems to be working fine now on Vercel live site. Once the user logs in they are redirected to "my-project/suggestions". On this page I am using getServerSideProps to identify if there is a valid session token. If so, data is pulled from a local json file.
On the live site, when the user logs in, the page is redirected to "/suggestions", yet I am receiving an 500 Internal Server Error page. On the function logs I am getting this error message:
[GET] /_next/data/KpsnuV9k44lUAhQ-0rK-B/suggestions.json
10:10:57:12
2022-05-05T14:10:59.270Z 5b7a7375-045f-4518-864b-7968c3c9385f ERROR [Error: ENOENT: no such file or directory, open '/var/task/public/data/data.json'] {
errno: -2,
syscall: 'open',
path: '/var/task/public/data/data.json',
page: '/suggestions'
}
RequestId: 5b7a7375-045f-4518-864b-7968c3c9385f Error: Runtime exited with error: exit status 1
Runtime.ExitError
This is my first project using MongoDB and Next-Auth.. not so sure what the issue is in this case. In my .env.local file I only have these two variables:
NEXTAUTH_SECRET="MUNKNATION"
NEXTAUTH_URL=http://localhost:3000
How I am pulling the data on local host:
export const getServerSideProps = async (context) => {
const session = await getSession({ req: context.req });
if (!session) {
return {
redirect: {
destination: "/",
permanent: false,
},
};
} else {
let filePath = path.join(process.cwd(), "public", "data", "data.json");
let jsonData = await fs.readFile(filePath);
const data = JSON.parse(jsonData);
const inProgressStatusData = data.productRequests.filter(
(item) => item.status == "in-progress"
);
const liveStatusData = data.productRequests.filter(
(item) => item.status == "live"
);
const plannedStatusData = data.productRequests.filter(
(item) => item.status == "planned"
);
let filterData = filteredData(data, "suggestion");
let feedbackData = {
suggestions: filterData,
progress: inProgressStatusData,
planned: plannedStatusData,
live: liveStatusData,
};
return {
props: { session, feedbackData },
};
}
};
Folder structure:
A simple solution to this problem would be to, inside of your getServerSideProps, instead of calling readFile use readFileSync as follows:
export const getServerSideProps = async (context) => {
...
const file = readFileSync(
join(process.cwd(), "public", "data", "data.json"),
"utf8"
);
const data = JSON.parse(fileData);
...
I have tested this solution with Vercel and it works correctly, in development and production mode.

ionic serve complains about valid javascript "Parsing error: Unexpected token ="

I have a vuex-orm model called Profile.js
import { Model } from '#vuex-orm/core'
export default class Profile extends Model {
static entity = 'profile'
static fields () {
return {
id: this.uid(),
// etc...
}
}
}
When I run ionic serve I get the following output:
Build finished at 14:20:05 by 0.000s
[INFO] Browser window opened to http://localhost:4200!
ERROR in
[vue-cli-service] /home/user/IonicProjects/ionic/iloveu/src/store/models/Profile.js
[vue-cli-service] 4:19 error Parsing error: Unexpected token =
[vue-cli-service]
[vue-cli-service] ✖ 1 problem (1 error, 0 warnings)
[vue-cli-service]
[vue-cli-service] webpack compiled with 1 error
So it complains about this line
static entity = 'profile'
which is perfectly valid javascript or ecmascript.
What can I do so this valid code is not being tagged as erroneous?
my .eslintrc
module.exports = {
root: true,
env: {
node: true
},
'extends': [
'plugin:vue/vue3-essential',
'prettier'
],
parserOptions: {
ecmaVersion: 2020
},
rules: {
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'vue/no-deprecated-slot-attribute': 'off'
},
overrides: [
{
files: [
'**/__tests__/*.{j,t}s?(x)',
'**/tests/unit/**/*.spec.{j,t}s?(x)'
],
env: {
jest: true
}
}
]
}
reference to the vuex-orm documentation
Seems like this is the culprint
parserOptions: {
ecmaVersion: 2020
},
changing it to
parserOptions: {
ecmaVersion: 2022
},
does not return this error anymore, which is weird because the Quasar framework uses ecmaVersion: 2018 and does not have this error.

Integrating opbeat with sails

I'm trying to integrate opbeat with sails.js. They have a node.js client which includes middleware support for Connect and Express.
I've tried to create a custom middleware in http.js
module.exports.http = {
middleware: {
opbeat : require('opbeat')({
organizationId: '...',
appId: '...',
secretToken: '...'
}),
order: [
'opbeat',
'startRequestTimer',
'cookieParser',
'session',
'myRequestLogger',
'bodyParser',
'handleBodyParserError',
'compress',
'methodOverride',
'poweredBy',
'$custom',
'router',
'www',
'favicon',
'404',
'500'
],
}
};
Unfortunately it doesn't work. If you could please help point me in the right direction.
The value returned from the initializer function isn't a proper middleware function (it's just an Opbeat client). To get the middleware function, call middleware.connect() on the client:
var opbeat = require('opbeat')({
organizationId: '...',
appId: '...',
secretToken: '...'
})
module.exports.http = {
middleware: {
opbeat: opbeat.middleware.connect(), // get the Opbeat middleware function
order: [
... // put the bulk of your middleware here
'opbeat'
]
}
}
P.S. The function is called middleware.connect() because it was the connect module that set the standard of having a middleware function that expects the 3 arguments; Request, Response and Callback. An alias exists that is called middleware.express() - but it's just that: An alias.
Update:
I reversed the order of the middleware in the example above so that Opbeat is placed at the end. This is important to that that it can catch errors tickling down the middleware-chain.

ExtJS: Rest Proxy Post Data Failure

Hy,
I've a Problem by sending data via ExtJs Rest Proxy. When I POST Data I get the Exception
in Chrome: Uncaught TypeError: Cannot read property 'clientIdProperty' of undefined
in Firefox: TypeError: clientRecords[0] is undefined
My Store
Ext.define('Test.store.Test', {
extend: 'Ext.data.Store',
requires: [
'Test.model.test',
'Ext.data.proxy.Rest',
'Ext.data.reader.Json'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
storeId: 'Test',
model: 'Test.model.test',
proxy: {
type: 'rest',
url: '/resources/php/test.php',
reader: {
type: 'json'
}
}
}, cfg)]);
}
My Model
Ext.define('Test.model.test', {
extend: 'Ext.data.Model',
requires: [
'Ext.data.field.Field'
],
fields: [
{
name: 'Test'
}
]
Is there a standard answer from Server?
I hope some one can Help me
Thx for Help
In your reader config, provide a 'root' property.
In ext 4.x it'll be like
reader: {
type: 'json',
root: 'root'
}
And in Ext 5.x, it'll be
reader: {
type: 'json',
rootProperty: 'root'
}
Here's what API doc says -
rootProperty : String The name of the property which contains the data
items corresponding to the Model(s) for which this Reader is
configured. For JSON reader it's a property name (or a dot-separated
list of property names if the root is nested). For XML reader it's a
CSS selector. For Array reader the root is not applicable since the
data is assumed to be a single-level array of arrays.
By default the natural root of the data will be used: the root JSON
array, the root XML element, or the array.
The data packet value for this property should be an empty array to
clear the data or show no data.
Defaults to: ''
For example, if the JSON response from the server is
{
"data": {
"Test": "TEST"
},
"someOtherField": "Some Value"
}
then, your rootProperty/ root will become -
rootProperty: 'data'
- Since data corresponds to your model

Cannot save a document in Mongoose - Validator required failed for path error

Following is my schema:
var userSchema = new Schema({
username: {
type: String,
required: true
},
password: {
type: String,
required: false
}
});
Now, when I attempt to save a document of the above schema, I get the following error:
{ message: 'Validation failed',
name: 'ValidationError',
errors:
{ username:
{ message: 'Validator "required" failed for path username',
name: 'ValidatorError',
path: 'username',
type: 'required' } } }
The above is the error object returned by mongoose upon save. I searched for this error but could not understand what is wrong. The document that I am trying to save is as follows:
{
username: "foo"
password: "bar"
}
Any idea what this means? I searched the mongoose docs too but could not find anything under the validation section.
First, you are missing a comma (,) after foo.
Now, is { username: "foo", password: "bar" } JSON sent via http, our an actual object in your server-side code ?
If it is, try to console.log(youVariable.username) and see if it shows undefined or the value foo. If you see undefined, then your object is not parsed properly.
You can make sure that whom ever is sending the POST request is sending a "application/json" in the header, you could be receiving something else, thus your JSON isn't parsed to a valid javascript object.