sails model is getting unrecognized datastore error on nested await method call - sails.js

I just cant figure out why this fails where it does.
This code is in a sails model called in Job.js
The Init() is called from bootstrap.js
This is all based on the ORM adapter sails-disk.
Init: async function() {
_jobRunner();
},
_jobRunner: function() {
async function doJobRunner() {
let job = await Job.findOne({state: 'inactive'});
let updated = await Job.Update(job);
}
setInterval(doJobRunner,3000);
},
Update: async function(job) {
let query = {id:job.id}
let updates,updated;
try {
let origJob = await Job.findOne(query); <-- success
updates = {status: 'active'} <-- added for illustration
updated = await Job.updateOne(query).set(updates); <----- this fails into catch (why?)
Job.publish(job.id,updated); // notify
} catch(err) {
sails.log.error(err);
}
return updated;
},
the Error is (err):
Unexpected error from database adapter: Unrecognized datastore: `default`, It doesn't seem to have been registered with this adapter (sails-disk).'
modelIdentity:'job'
**Node version**: v14.17.4
**Sails version** _(sails)_: 1.4.4
**ORM hook version** _(sails-hook-orm)_: 3.0.2
**sails-disk**_: 2.1.0

Related

NestJS: handle external API call (success or fail ) in a controller

The controller method:
/** Create a comment in database */
#ApiOperation({ summary: 'Create a comment in database' })
#Post()
async createComment(
#Query('callId', ParseIntPipe) callId: number,
#Body() dto: CreateCommentDto,
) {
const foundCall = await this.callService.getCall(callId);
if(!foundCall)
throw new NotFoundException('Call not found for this id');
if(!foundCall.crmActivityId)
throw new PreconditionFailedException('crmActivityId must exist for this operation.');
const activityNote = utilsFinalActivityNote(foundCall, dto.message);
// handle PUT service call method if fails
await this.pipeDriveService.putActivity(foundCall.crmActivityId, activityNote);
const comment: Partial<Comment> = {
callId: callId,
message: dto.message
};
// comment we still be saving even if putActivity fails
await this.commentService.createComment(comment);
}
The service method:
async putActivity(id: string, body) {
try {
await this.http.put(
`${process.env.PIPE_DRIVE_BASE_URL}/activities/${id}?api_token=${process.env.PIPE_DRIVE_API_KEY}`,
{ note: body}
).toPromise();
} catch (e) {
throw new PreconditionFailedException(e.response.data.message);
}
}
If the external API call fail it will still save the comment in the database.
How to handle error if my external API call fail ?

Is there a mongodb server for Cypress to be able to query inside my tests

I need to query mongo inside my Cypress tests to basically see if my POST is updating some fields, but I don't see a npm package for it like there is for sql server. Googling it I only see documentation and examples on how to seed the db.
Any thoughts, comments?
Thank you
Take a look at this post: https://glebbahmutov.com/blog/testing-mongo-with-cypress/
The gist of it:
-- plugins/index.js
/// <reference types="cypress" />
const { connect } = require('../../db')
module.exports = async (on, config) => {
const db = await connect()
const pizzas = db.collection('pizzas')
on('task', {
async clearPizzas() {
console.log('clear pizzas')
await pizzas.remove({})
return null
},
})
}
-- db.js
const { MongoClient } = require('mongodb')
const uri = process.env.MONGO_URI
if (!uri) {
throw new Error('Missing MONGO_URI')
}
const client = new MongoClient(uri)
async function connect() {
// Connect the client to the server
await client.connect()
return client.db('foods')
}
async function disconnect() {
// Ensures that the client will close when you finish/error
await client.close()
}
module.exports = { connect, disconnect }
Change the line await pizzas.remove({}) to whatever query you want to run, I'll assume you know how to get the result of the query and assert it.

Post Api not return any response in nest js

I use nestjs and psql and I want upload files and save the url in the database . when I run the api , data save on db but it doesn’t return any response .
this is my service:
async uploadFiles(files){
if (!files) {
throw new HttpException(
{
errorCode: UploadApplyOppErrorEnum.FileIsNotValid,
message: UploadApplyOppMsgEnum.FileIsNotValid,
},
HttpStatus.UNPROCESSABLE_ENTITY,
);
}
const filedata = OrderFilesData(files);
return filedata.map(async(filePath) => {
let orderFile = new OrderFile();
orderFile.fileUrl = filePath.fileUrl;
orderFile.type = filePath.fileType;
try {
let result = await this.orderFileRepository.save(orderFile);
return await result
} catch (error) {
throw new BadRequestException(error.detail);
}
});
}
and this is my controller
#UploadOrderFilesDec()
#Post('upload')
uploadFiles(#UploadedFiles() files){
return this.ordersService.uploadFiles(files);
}
You can't return an array of async methods without using Promise.all(), otherwise the promises haven't resolved yet. You can either use return Promise.all(fileData.map(asyncFileMappingFunction)) or you can use a regular for loop and await over the results.

mongo db transaction with multiple collection not working

the following function is supposed to do:
save the project into collection 'project_list'
push the uuid of the new project to a client in the collection 'client_list'
with transaction enabled, if anything goes wrong (such as the client id is given in the new project JSON object does not exist in the collection 'client_list'), then both step1 and step2 will be canceled.
noticed that the code is giving the client_id as 'invalid-uuid' to updateOne which will not add the project uuid to the client because the client_id does not exist in the collection but the new project is saved into collection 'project_list' with or without me doing commitTransaction.
I was reading this https://mongoosejs.com/docs/transactions.html which suggest me to abort the transaction by calling await session.abortTransaction(); but i dont know how to implement it.
thanks in advance.
transactionCreateProject: async function (newProjectJson) {
const mongoConnectConfig = {useNewUrlParser: true, useUnifiedTopology: true};
await mongoose.connect(CONSTANTS.ADMIN_MONGO_URL, mongoConnectConfig)
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'))
db.once("open", function (callback) {
console.log("Connection Succeeded")
});
let project = mongoose.model('project', mongooseProjectSchema)
let client = mongoose.model('client', mongooseClientSchema)
const session = await mongoose.startSession();
session.startTransaction();
try {
console.log(newProjectJson.clientUUID)
let newProjectMongooseObject = new project()
for (let i = 0; i < Object.keys(newProjectJson).length; i++){
// assigning the attributes of new project to mongoose object
newProjectMongooseObject[Object.keys(newProjectJson)[i]] = newProjectJson[Object.keys(newProjectJson)[i]]
}
newProjectMongooseObject['createdAt'] = dateObject.toISOString();
let saveRes = await newProjectMongooseObject.save()
let addProjectToClientRes = await clientMongooseModel.updateOne({ 'uuid': "invalid-uuid"}, {$push: {'projects': { projectID: newProjectJson.uuid}}})
}
catch (e) {
console.log(e)
return null
}
finally {
console.log("in finally, session ending")
session.endSession();
}
return null
},

Issue Connecting to MongoDB collections

I am using axios and express.js API to connect to my mongo DB. I have a .get() request that works for one collection and doesn't work for any other collection. This currently will connect to the database and can access one of the collections called users. I have another collection setup under the same database called tasks, I have both users and tasks setup the same way and being used the same way in the code. The users can connect to the DB (get, post) and the tasks fails to connect to the collection when calling the get or the post functions. When viewing the .get() API request in the browser it just hangs and never returns anything or finishes the request.
any help would be greatly appreciated!
The project is on GitHub under SCRUM-150.
API connection
MONGO_URI=mongodb://localhost:27017/mydb
Working
methods: {
//load all users from DB, we call this often to make sure the data is up to date
load() {
http
.get("users")
.then(response => {
this.users = response.data.users;
})
.catch(e => {
this.errors.push(e);
});
},
//opens delete dialog
setupDelete(user) {
this.userToDelete = user;
this.deleteDialog = true;
},
//opens edit dialog
setupEdit(user) {
Object.keys(user).forEach(key => {
this.userToEdit[key] = user[key];
});
this.editName = user.name;
this.editDialog = true;
},
//build the alert info for us
//Will emit an alert, followed by a boolean for success, the type of call made, and the name of the
//resource we are working on
alert(success, callName, resource) {
console.log('Page Alerting')
this.$emit('alert', success, callName, resource)
this.load()
}
},
//get those users
mounted() {
this.load();
}
};
Broken
methods: {
//load all tasks from DB, we call this often to make sure the data is up to date
load() {
http
.get("tasks")
.then(response => {
this.tasks = response.data.tasks
})
.catch(e => {
this.errors.push(e);
});
},
//opens delete dialog
setupDelete(tasks) {
this.taskToDelete = tasks;
this.deleteDialog = true;
},
//opens edit dialog
setupEdit(tasks) {
Object.keys(tasks).forEach(key => {
this.taskToEdit[key] = tasks[key];
});
this.editName = tasks.name;
this.editDialog = true;
},
//build the alert info for us
//Will emit an alert, followed by a boolean for success, the type of call made, and the name of the
//resource we are working on
alert(success, callName, resource) {
console.log('Page Alerting')
this.$emit('alert', success, callName, resource)
this.load()
}
},
//get those tasks
mounted() {
this.load();
}
};
Are you setting any access controls in the code?
Also refer to mongoDB's documentation here:
https://docs.mongodb.com/manual/core/collection-level-access-control/
Here is my solution:
In your app.js, have this:
let mongoose = require('mongoose');
mongoose.connect('Your/Database/Url', {
keepAlive : true,
reconnectTries: 2,
useMongoClient: true
});
In your route have this:
let mongoose = require('mongoose');
let db = mongoose.connection;
fetchAndSendDatabase('yourCollectionName', db);
function fetchAndSendDatabase(dbName, db) {
db.collection(dbName).find({}).toArray(function(err, result) {
if( err ) {
console.log("couldn't get database items. " + err);
}
else {
console.log('Database received successfully');
}
});
}