Search code examples
vue.jsnuxt.jsurl-parametersserver-side-scriptingnuxt-content

Using $contains in a Nuxt Content API query


I am attempting to retrieve only blog posts (in my /content directory) that contain a certain tag in my Nuxt Content query. Due to the fact I am using a URL Query Parameter in my Nuxt Content query string I am having to use the API that Nuxt Content creates (documented here).

Unfortunately I can't see any documentation on how to use the $contains parameter of the where clause inside the query which is usable if you use the server-side version (using queryContent, as documented here).

My current code (below) is returning an empty data set which I believe means I'm using the correct syntax (otherwise I'd get a 'Bad Request' error, but it's not returning any content, which isn't what I expect as I've checked the tag I'm passing through and I definitely have blog posts that are tagged with that tag.

<script setup> on blog/index.vue

const getPostsByTag = async (tag) => {
  const postsArr = await fetch(`/api/_content/query?_params={"where":{"tags":{"_contains":"${tag}"}}}`).then(res => res.json())
  return postsArr
}

example blog post in content/testing

---
title: 'Test 1'
slug: 'test-1'
tags: [ 'test' ]
excerpt: "lorem ipsum dolor sit amet consectetur adipiscing elit non nobis domine"
created: '2023-03-08'
updated: '2023-03-12'
---

<p>Cupcake ipsum dolor sit amet soufflé icing carrot cake marshmallow. Chupa chups marshmallow dragée candy canes danish muffin dragée tootsie roll lollipop. Marshmallow lemon drops cake pudding powder muffin oat cake apple pie tiramisu. Powder liquorice gummies marshmallow toffee gummies danish sugar plum sweet. Lollipop candy jelly topping cake cake. Jelly beans pudding bonbon pastry cake icing biscuit. Soufflé lollipop jelly candy canes tart.</p>

I'm very aware I could be barking up the wrong tree and I can, in fact, access query parameters via the <script setup> which would be immensely useful so if that is the case, please let me know!


Solution

  • I considered deleting this question as the answer was in fact very simple, but I've decided I'll answer it instead in case anyone else has the same issue. You can just pass the url parameter retrieved from the front-end script to the back-end script and it will stil work. This question seems to have arisen more from my fundamental misunderstanding of Nuxt/Vue

    const getPostsByTag = async (tag) => {
      return queryContent().where({ 'tags': { $contains: tag } }).find()
    }