Virtual Field Querying

default discord avatar
TheDuncolast year
8

@jesschow I'm attempting to make a virtual field for if my scheduled content is live in production that I can query off of instead of passing along all of these parameters as query variables.



This is how the field is set up...


{
    name: 'prodPublished',
    type: 'checkbox',
    admin: {
        position: 'sidebar',
        readOnly: true,
    },
    hooks: {
        beforeChange: [
            ({ siblingData }) => {
                delete siblingData['prodPublished'];
            },
        ],
        afterRead: [
            ({ data }) => {
                if (data.forcePublished) {
                    return true;
                }

                const now = new Date();

                if (data.status === 'published' && data.publishedDate <= now.toISOString()) {
                    return true;
                }

                return false;
            },
        ],
    },
}


I'm a bit confused because when I query for it with the query I would expect to work it doesn't return anything (pictured).



GraphQL doesn't seem to think the field exists...



But it still appears in the schema and in the query when I actually am able to get data from it (by querying for when that field doesn't exist)



Could you explain what's going on here? Why isn't this behaving as I would expect?

  • default discord avatar
    Jarrodlast year

    The data is not in the database, so you cannot filter on a virtual field. If it is something you would like to filter on, you will want to store the data in the db (don’t delete from sibling data).

  • default discord avatar
    TheDuncolast year

    Ah, I was confused because I had actually tried removing that beforeChange hook previously to no avail, but I had forgotten to actually save the document in Payload which caused it to remain out of the database. It all makes sense now, thanks!



    I was also under the very false assumption that queries and such from the GraphQL API went through Payload's hooks first, but now I know they hit the db directly (which does make sense).

  • default discord avatar
    Jarrodlast year

    GraphQL does go through hooks!

  • default discord avatar
    TheDuncolast year

    Oh? Then why did it not work when it wasn't in the database?

  • default discord avatar
    Jarrodlast year

    bc you cannot filter on data that does not exist



    Virtual fields are calculated on the fly, when the request comes in. To filter on data it must be in the db

  • default discord avatar
    TheDuncolast year

    Ah, yeah that explains it. Makes sense, thanks!

Star on GitHub

Star

Chat on Discord

Discord

online

Can't find what you're looking for?

Get help straight from the Payload team with an Enterprise License.