Anyone have a decent approach to omit certain fiel...
# orm-help
i
Anyone have a decent approach to omit certain fields from Prisma/Express?
m
do you want a general filter that isn't just
select?
i
Yeah
Basically, remove
password
from
User
unless I explicitly select it
m
hmm maybe Prisma middleware can do this
y
I also agree with @Meiri Anto opinion see Middleware-Running Order https://www.prisma.io/docs/concepts/components/prisma-client/middleware is there any other reason not in resolver ? (omit certain fields)
m
FYI how I do something like this in my code is set authorization at the GraphQL layer instead of the Prisma layer
b
You can create a default JS object as a schema and import it in your getUser function.
Copy code
import userSchema from '@schemas/user';

const getUser = async (id, select = {})=> {
  const user = await prisma.users.findUnique({
    where: {
      id: id
    },
    select: {
      ...userSchema, // Default schema
      ...select // Overwrites / adds keys on the default schema
    }
  });

  return user;
}
Copy code
// @schemas/user.js

export default {
  name: true,
  email: true,
};
Now you can call the getUser function with or without the password:
Copy code
// No password
const user = await getUser(id);

// With password
const user = await getUser(id, { password: true });
m
Expliciting using
select
only retrieves only the fields you want (
: true
) ignoring every other fields not included in `select`:
const userWithoutPassword = await context.prisma.user.findUnique({
where: {
Copy code
email: “<mailto:you@yourcompany.com|you@yourcompany.com>”
      },
select: {
email: true,
country: true,
Copy code
isProfileActive: true
         // password: false
canReceiveNewsletter: true,
}
})
console.log(userWithoutPassword.password) // => null
@Bård Your solution looks neat!
b
@Martïn Cheers!