Skip to content

Instantly share code, notes, and snippets.

@jhahspu
Last active February 2, 2025 20:22
Show Gist options
  • Save jhahspu/6f7a374d5a74162058ed39f872758344 to your computer and use it in GitHub Desktop.
Save jhahspu/6f7a374d5a74162058ed39f872758344 to your computer and use it in GitHub Desktop.
Strapi
// let existingProd = await strapi.db.query("api::product.product").findOne({
//   where: {iiqID: product.iiqID},
// })

// if (existingProd) {
//   await strapi.db.query('api::product.product').update({
//     where: { iiqID: product.iiqID },
//     data: {...product},
//   })

//   updates++
// } else {
//   await strapi.db.query('api::product.product').create({
//     data: {...product}
//   })
//   newCount += 1
//   newSKUs = [...newSKUs, product.sku]
// }


// let existingProd = await strapi.db.query("api::product.product").findOne({
//   where: {sku: product.sku},
// })
// if (existingProd) {
//   await strapi.db.query('api::product.product').update({
//     where: { sku: product.sku },
//     data: {...product},
//   })

//   updates++
// } else {
//   notFound = [...notFound, product.sku]
// }


async beforeUpdate(event) {
    const { where, data } = event.params

    if (data.slug && data.slug.trim() !== "") {
      const currentProduct = await strapi.entityService.findOne('api::product.product', where.id, {
        fields: ["slug", "oldSlugs"]
      })

      if (currentProduct.slug && currentProduct.slug !== data.slug) {
        let oldSlugs = currentProduct.oldSlugs as string[]

        if (oldSlugs === null) {
          const forUpdate = { oldSlugs: [currentProduct.slug] }
          strapi.entityService.update('api::product.product', where.id, {
            data: { ...forUpdate }
          })
        } else if (!oldSlugs.some(slug => slug === currentProduct.slug)) {
          oldSlugs.push(currentProduct.slug)
          const forUpdate = { oldSlugs: [...oldSlugs]}
          strapi.entityService.update('api::product.product', where.id, {
            data: { ...forUpdate }
          })
        }
      }
    }
  }


async updater(ctx) {
    const { products } = ctx.request.body;

    if (!Array.isArray(products)) {
      return ctx.badRequest("expected products, got something else...")
    }

    let updatePromises: Promise<void>[] = []
    let errors: {sku: string; error: string}[] = []

    const newSKUs = []
    let updates = 0
    let newCount = 0

    products.forEach((product) => {
      const updatePromise = (async () => {
        try {
          const existingProd = await strapi.entityService.findMany("api::product.product", {
            filters: { iiqID: {$eq: product.iiqID} },
            limit: 1
          })
          if (existingProd.length > 0) {
            await strapi.entityService.update('api::product.product', existingProd[0].id, {
              data: { ...product }
            })
            updates++
          } else {
            await strapi.entityService.create("api::product.product", {
              data: { ...product }
            })
            newCount++
            newSKUs.push(product.sku)
          }
        } catch (error) {
          errors.push({sku:product.sku, error: error.message})
        }
      })()

      updatePromises.push(updatePromise)
    })

    Promise.all(updatePromises).then(() => {
      console.log(`\n\n\toperations completed! newCount: ${newCount} | updates: ${updates} | new SKUs: ${newSKUs}\n\n`)
      strapi.entityService.create("api::web-updater.web-updater", {
        data: {
          message: `processed: ${products.length}`,
          updated: updates,
          newProducts: newCount,
          newSKUs: newSKUs
        }
      })
    })

    // Respond immediately
    ctx.send({ message: `received for update ${products.length}`, errorsEncountered: errors.length })

    // Log errors asynchronously
    setImmediate(() => {
      if (errors.length > 0) {
        console.error('Errors encountered during updates:', errors)
      }
    })
  },

  async manualUpdater(ctx) {
    const {products} = ctx.request.body;

    try {
      let notFound = []
      let updates = 0

      await Promise.all(products.map(async (product) => {
        const existingProd = await strapi.entityService.findMany("api::product.product", {
          filters: { sku: {$eq: product.sku} },
          limit: 1
        })

        if (existingProd.length > 0) {
          await strapi.entityService.update('api::product.product', existingProd[0].id, {
            data: { ...product }
          })
          updates++
        } else {
          notFound.push(product.sku)
        }
      }))
      ctx.send({message: "update successful", updated: updates, notFound: notFound})
    } catch (error) {
      console.error(error)
      ctx.throw(500, "error updater", {error})
    }
  },

APP Settings

  • /api/apps/1
{
  fields:["name", "description", "currency", "exchangeRate", "vat", "allowSale", "menu", "footer"],
  populate: {
    logo: {
      fields: ["alternativeText", "url"]
    },
    landing_page: {
      populate: {
        metadata: {
          populate: {
            metaImage: {
              populate: true,
              fields: ["alternativeText", "url"]
            }
          }
        },
        blocks: {
          populate: {
            image: {
              fields: ["alternativeText", "url", "formats"]
            },
            cta: {
              fields: ["text", "action", "iconPosition", "css"],
              populate: {
                icon: {
                  fields: ["alternativeText", "url"]
                }
              }
            },
            slide: {
              fields: ["internalLink", "name", "buttonText", "campaign", "textColor", "umami"],
              populate: {
                imageDesktop: {
                  fields: ["alternativeText", "url", "width", "height"]
                },
                imageMobile: {
                  fields: ["alternativeText", "url", "width", "height"]
                }
              }
            },
            products: {
              fields: ["isNew", "title", "slug", "stock", "allowedForSale", "price", "priceInCents", "discount", "shipping", "sku", "iiqID", "energyClass"],
              populate: {
                images: {
                  fields: ["alternativeText", "url", "formats"]
                },
                eprelLabel: {
                  fields: ["alternativeText", "url"]
                }
              }
            },
            categories: {
              fields: ["name", "slug"],
              populate: {
                image: {
                  fields: ["alternativeText", "url"]
                }
              }
            },
            brands: {
              fields: ["name", "slug"],
              populate: {
                logo: {
                  fields: ["alternativeText", "url"]
                }
              }
            },
            blogs: {
              fields: ["title", "slug", "intro"],
              populate: {
                image: {
                  fields: ["alternativeText", "url"]
                }
              }
            },
            twinCards: {
              populate: {
                image: {
                  fields: ["alternativeText", "url"]
                }
              }
            }
          }
        }
      }
    }
  }
}

Landing

{
  populate: {
    metadata: {
      populate: {
        metaImage: {
          populate: true,
          fields: ["alternativeText", "url"]
        }
      }
    },
    blocks: {
      populate: {
        image: {
          fields: ["alternativeText", "url", "formats"]
        },
        cta: {
          fields: ["text", "action", "iconPosition", "css"],
          populate: {
            icon: {
              fields: ["alternativeText", "url"]
            }
          }
        },
        slide: {
          fields: ["internalLink", "name", "buttonText", "campaign", "textColor", "umami"],
          populate: {
            imageDesktop: {
              fields: ["alternativeText", "url", "width", "height"]
            },
            imageMobile: {
              fields: ["alternativeText", "url", "width", "height"]
            }
          }
        },
        products: {
          fields: ["isNew", "title", "slug", "stock", "allowedForSale", "price", "priceInCents", "discount", "shipping", "sku", "iiqID", "energyClass"],
          populate: {
            images: {
              fields: ["alternativeText", "url", "formats"]
            },
            eprelLabel: {
              fields: ["alternativeText", "url"]
            }
          }
        },
        categories: {
          fields: ["name", "slug"],
          populate: {
            image: {
              fields: ["alternativeText", "url"]
            }
          }
        },
        brands: {
          fields: ["name", "slug"],
          populate: {
            logo: {
              fields: ["alternativeText", "url"]
            }
          }
        },
        blogs: {
          fields: ["title", "slug", "intro"],
          populate: {
            image: {
              fields: ["alternativeText", "url"]
            }
          }
        },
        twinCards: {
          populate: {
            image: {
              fields: ["alternativeText", "url"]
            }
          }
        }
      }
    }
  }
}
  • api/apps/1
{
  fields:["menu"],
  populate: {
    products: {
      publicationState: 'live',
      fields: ["sku","slug"]
    }
  }
}

BLOG

All

  • /api/blogs
{
  publicationState: 'live',
  sort: ['publishedAt:desc'],
  fields: ["title", "slug", "intro"],
  populate: {
    image: {
      fields: ["alternativeText", "url"]
    }
  }
}

Single

  • /api/blogs
{
  filters: {
    slug: {
      $eq: 'innovative-electrical-solutions-for-green-energy',
    },
  },
  fields: ["title", "slug", "intro", "content", "updatedAt"],
  populate: {
    image: {
      fields: ["alternativeText", "url"]
    },
    blocks: {
      populate: {
        products: {
          fields: ["isNew", "title", "slug", "stock", "allowedForSale", "price", "priceInCents", "discount", "shipping", "sku", "iiqID", "energyClass"],
          populate: {
            images: {
              fields: ["alternativeText", "url", "formats"]
            },
            eprelLabel: {
              fields: ["alternativeText", "url"]
            }
          }
        },
        categories: {
          fields: ["name", "slug"],
          populate: {
            image: {
              fields: ["alternativeText", "url"]
            }
          }
        }
      }
    }
  }
}

Brands

All brands

  • /api/brands
{
  fields: ["name", "slug", "description"],
  populate: {
    logo: {
      fields: ["alternativeText", "url"]
    }
  }
}

Single Brands

  • /api/brands
{
  filters: {
    slug: {
      $eq: 'milwaukee',
    },
  },
  fields: ["name", "slug", "description"],
  populate: {
    logo: {
      fields: ["alternativeText", "url"]
    },
    products: {
      fields: ["isNew", "title", "slug", "stock", "allowedForSale", "price", "priceInCents", "discount", "shipping", "sku", "iiqID", "energyClass"],
      populate: {
        images: {
          fields: ["alternativeText", "url", "formats"]
        },
        eprelLabel: {
          fields: ["alternativeText", "url"]
        }
      }
    }
  }
}

Campaign

  • /api/promo
{
  filters: {
    slug: {
      $eq: 'cozy-home',
    },
  },
  fields: ["name", "slug", "end", "description"],
  populate: {
    image: {
      fields: ["alternativeText", "url", "width", "height"]
    },
    metadata: {
      populate: {
        metaImage: {
          populate: true,
          fields: ["alternativeText", "url", "formats"]
        }
      }
    },
    products: {
      fields: ["isNew", "title", "slug", "stock", "allowedForSale", "price", "priceInCents", "discount", "shipping", "sku", "iiqID", "energyClass"],
      populate: {
        images: {
          fields: ["alternativeText", "url", "formats"]
        },
        eprelLabel: {
          fields: ["alternativeText", "url"]
        }
      }
    },
    blocks: {
      populate: {
        desktop: {
          fields: ["alternativeText", "url", "width", "height", "formats"]
        },
        mobile: {
          fields: ["alternativeText", "url", "width", "height", "formats"]
        },
        items: {
          populate: {
            image: {
              fields: ["alternativeText", "url", "width", "height", "formats"]
            },
            product: {
              fields: ["isNew", "title", "slug", "stock", "allowedForSale", "price", "priceInCents", "discount", "shipping", "sku", "iiqID", "energyClass"],
              populate: {
                images: {
                  fields: ["alternativeText", "url", "formats"]
                },
                eprelLabel: {
                  fields: ["alternativeText", "url"]
                }
              }
            },
          }
        }
      }
    }
  }
}

Categories v2

  • /api/categories
{
  filters: {
    $and: [
      { slug: { $eq: 'surface-and-recessed' } }
    ]
  },
  publicationState: 'live',
  fields: ["name", "slug", "description", "filters"],
  populate: {
    image: {
      fields: ["alternativeText", "url"]
    },
    imageWide: {
      fields: ["alternativeText", "url"],
    },
    products: {
      sort: ["title:asc"],
      fields: ["isNew", "title", "slug", "stock", "allowedForSale", "price", "priceInCents", "discount", "shipping", "sku", "iiqID", "energyClass", "createdAt"],
      populate: {
        images: {
          fields: ["alternativeText", "url", "formats"]
        },
        eprelLabel: {
          fields: ["alternativeText", "url"]
        }
      }
    },
    blocks: {
      populate: {
        products: {
          fields: ["isNew", "title", "slug", "stock", "allowedForSale", "price", "priceInCents", "discount", "shipping", "sku", "iiqID", "energyClass"],
          populate: {
            images: {
              fields: ["alternativeText", "url", "formats"]
            },
            eprelLabel: {
              fields: ["alternativeText", "url"]
            }
          }
        },
        categories: {
          fields: ["name", "slug"],
          populate: {
            image: {
              fields: ["alternativeText", "url"]
            }
          }
        }
      }
    }
  }
}

Landing Page

  • /api/landing-pages/4
{
  populate: {
    metadata: {
      populate: {
        metaImage: {
          populate: true,
          fields: ["alternativeText", "url"]
        }
      }
    },
    blocks: {
      populate: {
        image: {
          fields: ["alternativeText", "url", "width", "height", "formats"]
        },
        ctaButton: {
          fields: ["text", "link", "color"],
        },
        twinCards: {
          populate: {
            image: {
              fields: ["alternativeText", "url", "width", "height", "formats"]
            }
          }
        },
        product: {
          fields: ["isNew", "title", "slug", "stock", "allowedForSale", "price", "priceInCents", "discount", "shipping", "sku", "iiqID", "energyClass"],
          populate: {
            images: {
              fields: ["alternativeText", "url", "formats"]
            },
            eprelLabel: {
              fields: ["alternativeText", "url"]
            }
          }
        },
        products: {
          fields: ["isNew", "title", "slug", "stock", "allowedForSale", "price", "priceInCents", "discount", "shipping", "sku", "iiqID", "energyClass"],
          populate: {
            images: {
              fields: ["alternativeText", "url", "formats"]
            },
            eprelLabel: {
              fields: ["alternativeText", "url"]
            }
          }
        },
        categories: {
          fields: ["name", "slug"],
          populate: {
            image: {
              fields: ["alternativeText", "url"]
            }
          }
        },
        brands: {
          fields: ["name", "slug"],
          populate: {
            logo: {
              fields: ["alternativeText", "url"]
            }
          }
        },
        blogs: {
          fields: ["title", "slug", "intro"],
          populate: {
            image: {
              fields: ["alternativeText", "url"]
            }
          }
        }
      },
    }
  }
}

Misc Pages

  • /api/misc-pages
{
  publicationState: 'live',
  filters: {
    $and: [
      { shop: { $eq: "EWuk" } },
      { slug: { $eq: "placing-an-order" } }
    ]
  },
  fields: ["shop", "slug", "title", "description", "content", "updatedAt"]
}

Products

  • /api/products
{
  publicationState: 'live',
  locale: ['en'],
  filters: {
    $or: [
      { title: { $containsi: "led" } },
      { shortDescription: { $containsi: "led" } },
      { sku: { $containsi: "led" } }
    ]
  },
  fields: ["isNew", "title", "slug", "stock", "allowedForSale", "price", "priceInCents", "discount", "shipping", "sku", "iiqID", "energyClass"],
  populate: {
    images: {
      fields: ["alternativeText", "url", "formats"]
    },
    eprelLabel: {
      fields: ["alternativeText", "url"]
    },
    categories: {
      fields: ["name", "slug"]
    }
  },
  pagination: {
    pageSize: 50,
    page: 1
  }
}

NEW

{
  publicationState: 'live',
  sort: ['title:asc'],
  filters: {
    isNew: true,
  },
  fields: ["isNew", "title", "slug", "stock", "allowedForSale", "price", "priceInCents", "discount", "shipping", "sku", "iiqID", "energyClass", "createdAt"],
  populate: {
    images: {
      fields: ["alternativeText", "url", "formats"]
    },
    eprelLabel: {
      fields: ["alternativeText", "url"]
    }
  }
}

SALE

{
  publicationState: 'live',
  sort: ['title:asc'],
  filters: {
    discount: {
      $gt: 0
    },
  },
  fields: ["isNew", "title", "slug", "stock", "allowedForSale", "price", "priceInCents", "discount", "shipping", "sku", "iiqID", "energyClass", "createdAt"],
  populate: {
    images: {
      fields: ["alternativeText", "url", "formats"]
    },
    eprelLabel: {
      fields: ["alternativeText", "url"]
    }
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment