Validate DTO in nestjs - nestjs

I'm using nest.js and typeORM to build my REST.API server. In my service I have some dto which comes from controller and make update in my db, but when I try to pass some unknown field in controller, I get an error:
EntityColumnNotFound: No entity column "hello" was found.at EntityColumnNotFound.TypeORMError [as constructor] (D
_
async edit(dto: EditThemeDto): Promise<Theme> {
const { id } = dto;
try {
await this.themeRepository.findOneOrFail(id);
} catch (e) {
throw new NotFoundException(e);
}
await this.themeRepository.update(id, dto);
return await this.themeRepository.findOne(id);
}
Is there proper way to validate input data dto to entity schema?

Related

Error: Actions must be plain objects. Instead, the actual type was: 'string'

Error:
Actions must be plain objects. Instead, the actual type was: 'string'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions.
The below code is the client side where I dispatch the selected user id to actions.
const friendHandle = (e) => {
e.preventDefault()
setSwitch(false)
setFriend(!friend)
dispatch(friendUser(id))//id is the id from params of selected users
setFetchAgain(!fetchAgain)
}
useEffect(() => {
if(currentUser){
currentUser?.friends?.map(friends => {
console.log(friends._id)
console.log(currentProfile._id)
if(friends._id===currentProfile._id){
return setFriend(true)
}
})
}else{
return setFriend(false)
}
},[currentUser,currentProfile])
below is actions.js for the above code
export const friendUser = (id) => async (dispatch) => {
try {
await api.friendUser(id)
dispatch(id)
} catch (error) {
console.log(error)
}
}
I am trying to pass the id of the selected user but I am getting an error. I am new to React so I am not able to understand.
remove the dispatch(id) from the action, might be some copy\paste or merge error

Find document from mongoose collections with specific condition

Recently I start using MongoDB with Mongoose on Nodejs.
This code works as it should, and returns me all data i need :
const getAllPosts = async () => {
try {
return (await PostModel.find().populate('user')).reverse();
} catch (error) {
console.log(error);
throw Error('Error while getting all posts');
}
};
But now I only need individual posts, which in the tags (represented as an array in the PostModel) contain the data that I will pass in the request.
For example, I will make a GET request to /posts/tag111 and should get all posts that have "tag111" in the tags array.
Any ways to do this?
If you are using expressjs, your route should be something like:
whatever.get('/:tag', postController.getAllPostTagged)
The function you use in your route (called getAllPostTagged above) should be similar to this one, in which you get the path param tag from req:
const postController = {
getAllPostTagged = async(req, res) => {
try {
return (await PostModel.find({tags: req.params.tag}));
} catch (error) {
console.log(error);
throw Error('Error while getting all posts');
}
}
}
The key here is to know where the params are obtained (from req.params) .

Can't access this.context inside a defined class and dataSources apollo-server-express

So my issue is trying to access the context inside this class. It always returns undefined. Now I tried working on this without the use of dataSources and everything works fine but once I introduce the dataSources inside apolloServer constructor, I can't access the context.
Here's my apolloServer constructor
This is where is define the apolloServer constructor
const server = new ApolloServer({
typeDefs,
resolvers,
dataSources: () => {
return {
usersApi: new UsersApi()
}
},
context:async({req,connection})=>{
if(connection){
return {
connection.context;
}
}else{
let user = req.user || "";
if(user){
let users = await Users.findOne({_id:req.user.id});
return {users}
}}
},
});
Heres my Resolver to handle fetching user details after signup
Here is one of my resolvers that resolves and fetches userdetails from the database
signUp:async(_,args,{ dataSources})=>{
return dataSources.usersApi.addUsers(args);
}
Here my class to handle this dataSource
Here I define my class that executes the function to return usersDetails such as name and email once the user is loggedin.
class UsersApi{
async getSignedUserDetails(){
if(!this.context.users){
throw new Error('Please signIn')
}
return await Users.find({_id:this.context.users.id});
}
}
If I remove anything to do with the context in other functions within the class above, it works.
I've looked at a tone of resources but not been able to solve it yet. Appreciate any help.

nodejs mongodb - how to return the inserted document using insertOne

I am using "mongodb": "^3.1.6",.
I have a method using the drivers insertOne method (shops is my mongoDb database collection):
/**
* Adds a new shop to the shops collection
* #param {Shop} doc - the new shop to add
*/
static async addShop(shop) {
try {
return await shops.insertOne(shop, {}, (err, result) => {
if (err) {
throw e
}
return result
})
// TODO this should return the new shop
} catch (e) {
console.error(`Something went wrong in addShop : ${e}`)
throw e
}
}
Now the method inserts the document into the collection as expected, but does not return the insert result. How do I return the result value of the callback function?
For reference - I wrote this unit test that I want to get to pass:
test("addShop returns the added shop", async () => {
const testShop = {
name: "Test shop for jest unit tests",
}
const newShop = await ShopsDAO.addShop(testShop)
const shoppingCart = global.DBClient.db(process.env.NS)
const collection = shoppingCart.collection("shops")
expect(newShop.name).toEqual(testShop.name)
await collection.remove({ name: testShop.name })
})
Thanks for the help.
I suggest you not to mix promises and callbacks as it is a bad way to organize your code. According to docs, if you do not pass callback insertOne will return Promise. So I suggest you to rewrite function smth like that:
static async addShop(shop) {
try {
return shops.insertOne(shop)
} catch (insertError) {
console.error(`Something went wrong in addShop : ${insertError}`)
throw insertError
}
}
This addShop will return promise, use await to retrieve data from it:
const newShop = await ShopsDAO.addShop(testShop)
P.S. You can also omit await with return statement

access state data from store into a string vue.js

Hey guys so I am trying to add state data from my store into a string in one of my axios calls within actions. Here is my store:
export const store = new Vuex.Store
({
state: {
participants: [],
filterTags: ["foo", "swag"],
page: 1,
perPage: 2,
filterTagName: "",
}
}
Here is my action call:
actions: {
async loadParticipants ({commit}) {
try {
console.log(this.state.page);
await axios
.get('/dash/participant?perPage=2&page=1&string=f')
.then(r => r.data)
.then(participants => {
console.log(participants.docs);
console.log("Hit me");
commit('setParticipants', participants)
})
}
catch (e) {
if (e.response)
console.log(e.response);
throw e
}
}
I want to add the store's state data where it says { INSERT DATA HERE } within the axios call:
.get('/dash/participant?perPage={INSERT DATA HERE }&page={ INSERT DATA HERE }&string=f')
Any input appreciated thank you!
In your action, you have access to the whole store, so instead to just getting only the commit declaring the param as ({commit}), you can add the state too:
async loadParticipants ({commit, state}) {
So you can use the state variable in your method body:
actions: {
async loadParticipants ({commit, state}) {
try {
console.log(this.state.page);
await axios
.get(`/dash/participant?perPage=${state.perPage}&page=${state.page}&string=${state.filterTagName}`)
.then(r => r.data)
.then(participants => {
console.log(participants.docs);
console.log("Hit me");
commit('setParticipants', participants)
})
}
catch (e) {
if (e.response)
console.log(e.response);
throw e
}
}
}
So you just want to fill your query params with the values from your vuex store?
Just pass the state into your action. And then you can add the state to your query params with a little help of template iterals. ${some-js-variable}
You can also directly destruct the response and grab the data.
Not sure why you make promise like then() statements if you use async and await.
actions: {
async loadParticipants ({commit, state}) {
try {
const {data} = await axios.get(`/dash/participant?perPage=${state.perPage}&page=${state.page}&string=f`)
console.log(data)
}
catch (e) {
if (e.response)
console.log(e.response);
throw e
}
}

Resources