How to correctly add and use Objection.js - node.js

I am trying to add Objection.js to my project (using ES6 "type": "module"), and getting this error which points to ./models/user.js:
import { Model } from "objection";
^^^^^
SyntaxError: The requested module 'objection' does not provide an export named 'Model'
Using the following code:
./methods.js
import User from "./models/user.js";
async function getInfo(idnum) {
const someUser = await User.query().findById(idnum);
return someUser;
}
./models/user.js
import db from "../connection.js";
import { Model } from "objection";
Model.knex(db);
class User extends Model {
static get tableName() {
return "users";
}
}
export default User;
./connection.js
const environment = process.env.NODE_ENV || "development";
import knexfile from "../knexfile.js";
const connection = knexfile[environment];
import knex from "knex";
const db = knex(connection);
export default db;
UPDATE
The creator of Objection.js said import { Model } from "objection" should work.
What am I doing wrong?

The only current workaround appears to be importing the Model like this:
import objection from "objection";
const { Model } = objection;
since Objection.js does exports like this:
export default { Model }
and not like this:
export { Model }

I hope that you are using a .mjs extension for the file if you are using import in a Node app.
But if you are using a .js as extension then you have to call that module using require.
const { Model } = require('objection');
This was the problem I once had... I don't know if this is the solution to your problem.

Related

How to solve this error (Nest & Prisma): ERROR [ExceptionsHandler] Cannot read properties of undefined (reading 'organ')

I'm developing an API using Nestjs and Prisma, the problem occurs when I try to insert information in the Database (Postgres), I get this error, saying that it cannot read the "organ" property which is the table in which I intend to insert the information.
The error is occurring in the repository in the create method:
`
import { Organ } from '#prisma/client';
import { CreateOrganDto } from '../../../../../modules/organs/dto/create-organ.dto';
import { IOrganRepository } from '../../../../../modules/organs/repositories/IOrganRepository';
import { PrismaService } from '../../../../../shared/infra/db/prisma.service';
export class OrganRepository implements IOrganRepository {
constructor(private prisma: PrismaService) {}
async create({ name }: CreateOrganDto): Promise<Organ> {
const organ = await this.prisma.organ.create({
data: {
name
},
});
return organ;
}
async findByName(name: string): Promise<Organ | null> {
const organ = await this.prisma.organ.findUnique({
where: {
name,
},
});
return organ;
}
}
`
a const organ dev
this.prisma.organ.create method is returning an Organ, never type when it should just return Organ
It looks like the PrismaClient is not in sync with Prisma Schema.
You would need to invoke npx prisma generate in order to regenerate the PrismaClient - Reference.
Also, I would recommend checking that all models defined in schema file has been created in the database, you can either use npx prisma migrate dev or npx prisma db push to create the corresponding tables - Reference.

vscode typescript intellisense for exported modules

IntelliSense works as expected in my main project file where I imported a third-party library to my project;
Example: I'm using a library "Directus," however, when exporting the class and importing in another file in my project, IntelliSense stops working.
import { Directus } from '#directus/sdk';
export class Editor {
public async directus(): Promise<any> {
let directus = new Directus("http://localhost:8055/");
await directus.auth.login({
email: "email#admin",
password: "password",
});
return directus
}
}
When importing the class in another file test.ts (IntelliSense stops working)
I'm not sure if this is a vscode issue or typescript configuration problem.
import { Editor } from ".";
let test = new Editor();
You are trying to access a property on an async method. Instead use this syntax:
const test = new Editor(); // create object instance
const directus = await test.directus(); // call method returning promise and await its value
directus.propertyName // access a property on the value
Thanks to #jsejcksn for pointing out that I needed to await for the method.
I have also needed to return the correct type, instead of using any returning TypeMap
import { Directus, TypeMap } from '#directus/sdk';
export class Editor {
public async directus(): Promise<Directus<TypeMap>> {
let directus = new Directus("http://localhost:8055/");
await directus.auth.login({
email: "email#admin",
password: "password",
});
return directus
}
}
Now IntelliSense works as expected.

Why I can not use " import { createSlice, configureStore } from '#reduxjs/toolkit' " in Node.js

guys
I am learning redux, and try to run a very simple example code in node.js environment. I got the following error when I try to use :
import { createSlice, configureStore } from '#reduxjs/toolkit' .
The errors is:
import { createSlice, configureStore } from '#reduxjs/toolkit'
^^^^^^^^^^^
SyntaxError: Named export 'createSlice' not found. The requested module '#reduxjs/toolkit' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:
import pkg from '#reduxjs/toolkit';
const { createSlice, configureStore } = pkg;
at ModuleJob._instantiate (internal/modules/esm/module_job.js:120:21)
at async ModuleJob.run (internal/modules/esm/module_job.js:165:5)
at async Loader.import (internal/modules/esm/loader.js:177:24)
at async Object.loadESM (internal/process/esm_loader.js:68:5)
If I use import like what the error tip says:
import pkg from '#reduxjs/toolkit';
const { createSlice, configureStore } = pkg;
All is OK.
What I want to ask is:
It gives me a wrong example in the official website of Redux? Or Just I run the example with a wrong way?
The following is the detail information.
My Node.js version is: v14.17.3
1 Init a node project:
mkdir redux_01
cd redux_01
yarn init
yarn add #reduxjs/toolkit
2 Modify the 'package.json', add a line in it:
"type":"module"
3 Create a file 'index.js' with the "Redux Toolkit Example" code parsed from https://redux.js.org/introduction/getting-started.
import { createSlice, configureStore } from '#reduxjs/toolkit'
const counterSlice = createSlice({
name: 'counter',
initialState: {
value: 0
},
reducers: {
incremented: state => {
// Redux Toolkit allows us to write "mutating" logic in reducers. It
// doesn't actually mutate the state because it uses the Immer library,
// which detects changes to a "draft state" and produces a brand new
// immutable state based off those changes
state.value += 1
},
decremented: state => {
state.value -= 1
}
}
})
export const { incremented, decremented } = counterSlice.actions
const store = configureStore({
reducer: counterSlice.reducer
})
// Can still subscribe to the store
store.subscribe(() => console.log(store.getState()))
// Still pass action objects to `dispatch`, but they're created for us
store.dispatch(incremented())
// {value: 1}
store.dispatch(incremented())
// {value: 2}
store.dispatch(decremented())
// {value: 1}
4 Now I run it like this:
node index.js
I then got that error message that I just mentioned.
The reason for the error is explained here:
https://lightrun.com/answers/reduxjs-redux-toolkit-cannot-import-redux-toolkit-from-a-nodejs-esm-module "here"
solution:
import * as toolkitRaw from '#reduxjs/toolkit';
const { createSlice,configureStore } = toolkitRaw.default ?? toolkitRaw;
or in Typescript:
import * as toolkitRaw from '#reduxjs/toolkit';

How to create lowdb in TypeScript(main.ts) Angular?

Creating Lowdb in Javascript working fine, I have searched in net, couldn't find proper(as per beginner's understanding) solution.
creating lowdb using Js
const low = require('lowdb')
const FileSync = require('lowdb/adapters/FileSync')
var customerpath = process.env.APPDATA+'/VEGFRUIT/Customer.json';
const cusadapter1 = new FileSync(customerpath)
const db = low(cusadapter1)
db.defaults({ customer: [{}]}).write();
how to convert above set of coding into Tyepscript?
1) perform this command
npm install --save #types/lowdb
2) this brief example class shows how to use lowdb in a typescript way
import lowdb from "lowdb";
import { default as FileAsync } from "lowdb/adapters/FileAsync";
export class DbService {
private db: lowdb.LowdbAsync<any>;
constructor(){
this.initDatabase();
}
private async initDatabase() {
const adapter = new FileAsync("db.json");
this.db = await lowdb(adapter);
}
private async SetSomeonesName(fullname: string): Promise<any> {
await this.db.set("user.fullname", fullname).write();
}
}

Import Module in ES6 Class Function

I have migrated my project to ESM and thus using .mjs in all my files in nodejs.
Previously in CommonJs, I could require a file right in the middle of a ES6 class function in order to load it only when needed.
module.exports = class Core{
constructor() {
this.init = this._init.bind(this)
return this.init()
}
async _init(){
const module = require('module')
//use required file/module here
}
}
But now when using Michael Jackson Scripts a.k.a .mjs, I cannot import a file on demand:
import Koa from 'koa'
export default = class Core{
constructor() {
this.init = this._init.bind(this)
return this.init()
}
async _init(){
import module from 'module'
//use imported file/module here
}
}
My app has many files/modules that are not consumed immediately, and can more can always be added in future, thus hardcoding the imports at the begining of the file is not an option.
Is there a way to import the files dynamically on demand when needed?
With a little modification from this answer, I managed to get it working via:
import Koa from 'koa'
export default = class Core{
constructor() {
this.init = this._init.bind(this)
return this.init()
}
async _init(){
const router = await import('./Router')
//use imported file/module here
}
}
Or you can use a promise if you are into that:
import('./router')
.then(something => {
//use imported module here
});
This suits me for now until the spec if finalised and shipped

Resources