CursosEmpresasBlogLiveConfPrecios

Filtros en Prisma

Clase 8 de 23 • Curso Avanzado de Node.js con GraphQL, Apollo Server y Prisma

Clase anteriorSiguiente clase
    Steve Anthony Luzquiños Agama

    Steve Anthony Luzquiños Agama

    student•
    hace 4 años

    Al hacer el include de los Attributes con Prisma, el tipo que se retorna ya no es solo Avocado, sino: Avocado & { attributes: Attributes | null }, así que deberíamos cambiar esto en el tipo de retorno de nuestros resolvers. El código final se vería algo como esto:

    import { Avocado, Attributes } from '@prisma/client' const getAllAvocados = async ( parent: unknown, args: unknown, { orm }: ResolverContext ): Promise<(Avocado & { attributes: Attributes | null })[]> => { try { return await orm.avocado.findMany({ include: { attributes: true } }) } catch (error) { console.error('Error getting all the avocados') console.error(error) throw error } } const getOneAvocado = async ( parent: unknown, { id }: { id: string }, { orm }: ResolverContext ): Promise< | (Avocado & { attributes: Attributes | null }) | null > => { try { return await orm.avocado.findUnique({ where: { id: parseInt(id) }, include: { attributes: true } }) } catch (error) { console.error('Error getting all the avocados') console.error(error) throw error } } export { getAllAvocados, getOneAvocado }
      Bruno Franco

      Bruno Franco

      student•
      hace 3 años
      import { createHash } from 'crypto' // import { Avocado } from './avocado.model' import type { Avocado, Attributes, PrismaClient } from '@prisma/client' type ResolverContext = { ormPrisma: PrismaClient } // function to findAll() with Prisma export async function findAll( parent: unknown, args: unknown, context: ResolverContext ): Promise<(Avocado & { attributes: Attributes | null })[] | null> { try { return await context.ormPrisma.avocado.findMany({ include: { attributes: true, }, }) } catch (error) { console.error('Error getting all the avocados') console.error(error) throw error } } export async function findOne( parent: unknown, args: { id: string }, context: ResolverContext ): Promise< | (Avocado & { attributes: Attributes | null }) | null > { try { return await context.ormPrisma.avocado.findUnique({ where: { id: parseInt(args.id) }, include: { attributes: true, }, }) } catch (error) { console.error('Error getting all the avocados') console.error(error) throw error } } export const resolver: Record< keyof (Avocado & { attributes: Attributes | null }), (parent: Avocado & { attributes: Attributes | null }) => unknown > = { id: (parent) => parent.id, createdAt: (parent) => parent.createdAt, updatedAt: (parent) => parent.updatedAt, deletedAt: (parent) => parent.deletedAt, sku: (parent) => parent.sku, name: (parent) => parent.name, price: (parent) => parent.price, image: (parent) => parent.image, attributes: (parent) => ({ description: parent.attributes?.description, shape: parent.attributes?.shape, hardiness: parent.attributes?.hardiness, taste: parent.attributes?.taste, }), } export async function createAvo( parent: unknown, { data }: { data: Pick<Avocado, 'name' | 'price' | 'image'> & Attributes }, context: ResolverContext ): Promise<Avocado> { const { name, price, image, ...attributes } = data return context.ormPrisma.avocado.create({ data: { name, price, image, sku: new Date().toISOString(), }, include: { attributes: true, }, }) }
    Emmanuel Rodríguez

    Emmanuel Rodríguez

    student•
    hace 4 años

    Inclusión de relaciones

    🚧 Documentación

    🛠 Commit

    . Con prisma, es posible manipular la respuesta deseada mediante dos opciones de retorno:

    1. Select - Para retornar campos específicos o de aquellos basadas en su relación.
    2. Include - Para incluir relaciones en la misma respuesta.

    . Ya que GraphQL permite dinámicamente seleccionar los campos, con Prisma solamente definimos que será tratado en el su request la distinción de dichos campos. . Por ejemplo, siguiendo la clase del profesor, anexo simplemente la opción include.

    // Account.model.ts export default class AccountModel extends Model<Account, Query, Payload> { // more code... /** * @description Find an account by id. * @param {Query} query * @returns Account */ async findUnique(query: Query): Promise<Account> { return await this.client.findUnique({ where: query, include: { directions: true }, }) } // more code... }

    Revisando que la referencia esté definida en el schema de graphql:

    type Account { id: ID! email: String! password: String! directions: [Direction] }
    Steve Anthony Luzquiños Agama

    Steve Anthony Luzquiños Agama

    student•
    hace 4 años

    El avocado del profesor:

    { "data": { "name": "Zutano Avocado", "price": 1.25, "image": "/images/zutano.jpg", "description": "The Zutano avocado is a cold hardy, consistent producing avocado variety. It resembles the Fuerte in appearance but is less flavorful but more cold hardy. The green fruits are abovate in shape with waxy bumps on the skin. The flesh has a low oil but high water content which causes it to have a more fibrous texture.", "shape": "Pear", "hardiness": "-5 ºC", "taste": "Splendid, is an avocado" } }
      José María C. L.

      José María C. L.

      student•
      hace 4 años

      Gracias mi buen

    José Luis Encastin Flores

    José Luis Encastin Flores

    student•
    hace 3 años

    Si prisma nos crea el tipado, ¿es recomendable incluir esquemas hechos con librerias como joi para la integridad de los datos?

    Luis Alfredo Hernández Duarte

    Luis Alfredo Hernández Duarte

    student•
    hace 3 años

    Siempre he pasado de string a int con el signo + ¿Hay alguna diferencia entre éste y ParseInt?

    ...findUnique({ where: { id: +args.id }})
      Jonathan 🦑 Alvarez

      Jonathan 🦑 Alvarez

      teacher•
      hace 3 años

      En general no pero no me sorprendería que hayan casos super específicos donde no sea igual. En todo caso, parseInt es mucho más explícito, y por ende más claro en su propósito que anteponer un "+"

    Juan Jose Rivas Álvarez

    Juan Jose Rivas Álvarez

    student•
    hace 2 años

    Como recomendacion para poder leer archivos json en el navegador de una mejor manera les recomiendo esta extencion extencion

    Fernando Quinteros Gutierrez

    Fernando Quinteros Gutierrez

    student•
    hace 3 años

    👉 El link para la API de los avocados

Escuelas

  • Desarrollo Web
  • English Academy
  • Marketing Digital
  • Inteligencia Artificial y Data Science
  • Ciberseguridad
  • Liderazgo y Habilidades Blandas
  • Diseño de Producto y UX
  • Contenido Audiovisual
  • Desarrollo Móvil
  • Diseño Gráfico y Arte Digital
  • Programación
  • Negocios
  • Blockchain y Web3
  • Recursos Humanos
  • Finanzas e Inversiones
  • Startups
  • Cloud Computing y DevOps

Platzi y comunidad

  • Platzi Business
  • Live Classes
  • Lanzamientos
  • Executive Program
  • Trabaja con nosotros
  • Podcast

Recursos

  • Manual de Marca

Soporte

  • Preguntas Frecuentes
  • Contáctanos

Legal

  • Términos y Condiciones
  • Privacidad
Reconocimientos
Reconocimientos
Logo reconocimientoTop 40 Mejores EdTech del mundo · 2024
Logo reconocimientoPrimera Startup Latina admitida en YC · 2014
Logo reconocimientoPrimera Startup EdTech · 2018
Logo reconocimientoCEO Ganador Medalla por la Educación T4 & HP · 2024
Logo reconocimientoCEO Mejor Emprendedor del año · 2024
De LATAM conpara el mundo
YoutubeInstagramLinkedInTikTokFacebookX (Twitter)Threads