# FindOrCreateMatch Query

**URL:** <https://forum.heroiclabs.com/t/findorcreatematch-query/4702>\
**Category:** Runtime Framework\
**Tags:** typescript\
**Created:** [December 7, 2023, 9:22am UTC](https://forum.heroiclabs.com/t/findorcreatematch-query/4702 "2023-12-07T09:22:16Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![Sathyaraj](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.heroiclabs.com/sathyaraj/32/1905_2.png) [@Sathyaraj](https://forum.heroiclabs.com/u/Sathyaraj)\
**Post date:** [December 7, 2023, 9:22am UTC](https://forum.heroiclabs.com/t/findorcreatematch-query/4702/1 "2023-12-07T09:22:16Z")

</div>

I am trying to create an online random game where first the player searches for existing online random games and join it else create a new match. but my query system is wrong. tried many things with no result. here is the code. can someone point out what the issue is here?

```auto
function rpcFindOrCreateMatchWithQuery(context: nkruntime.Context, logger: nkruntime.Logger, nk: nkruntime.Nakama, payload: string) {
    logger.info("rpcFindOrCreateMatchWithQuery.............................. " + payload);

    //In this line, you're type casting an empty object to RpcCreateMatchRequest. It doesn't actually create an instance of RpcCreateMatchRequest, it just treats the empty object as if it were an instance of RpcCreateMatchRequest.
    let request = {} as RpcCreateOnlineRandomMatchRequest;

    try {
        request = JSON.parse(payload);
        logger.info("rpcFindOrCreateMatchWithQuery request.............................. gameMode " + request.gameMode);
    } catch (error) {
        logger.error('........Error parsing json message: %q', error);
        throw error;
    }

    const query = `+label.gameMode:online_random`;
    logger.info("rpcFindOrCreateMatchWithQuery query.............................. " + query);
     let matches = nk.matchList(5, true, "", 2 ,4, query);

    logger.info("rpcFindOrCreateMatchWithQuery.............................. matches " + matches.length);
    // If matches exist, sort by match size and return the largest.
    if (matches.length > 0) {
        matches.sort(function (a, b) {
            return a.size >= b.size ? 1 : -1;
        });
        let matchId = matches[0].matchId;
        logger.debug('rpcFindOrCreateMatchWithQuery --> Found Match: ' + matchId);

        let response = {
            created: false,
            matchId: matchId
        };

        return JSON.stringify(response);
    }

    logger.debug('rpcFindOrCreateMatchWithQuery --> Did not find any Match Creating a new one.');

    let matchId = nk.matchCreate(online_random, { gameMode: online_random });
    logger.info("rpcFindOrCreateMatchWithQuery Created match.............................. matchId " + matchId);

    let response = {
        created: true,
        matchId: matchId
    };

    return JSON.stringify(response);
}

```

---

<div class="post-metadata">

**Author:** ![Sathyaraj](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.heroiclabs.com/sathyaraj/32/1905_2.png) [@Sathyaraj](https://forum.heroiclabs.com/u/Sathyaraj)\
**Post date:** [December 7, 2023, 10:35am UTC](https://forum.heroiclabs.com/t/findorcreatematch-query/4702/2 "2023-12-07T10:35:48Z")

</div>

The match Label is empty for the match created.  
 ![image](https://us1.discourse-cdn.com/flex020/uploads/heroiclabs/original/2X/3/341d078f023f3167bc877675cfa1bdf490577679.png)

Is this syntax wrong?

```auto
    let matchId = nk.matchCreate(online_random, { gameMode: online_random });

```

---

<div class="post-metadata">

**Author:** ![Sathyaraj](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.heroiclabs.com/sathyaraj/32/1905_2.png) [@Sathyaraj](https://forum.heroiclabs.com/u/Sathyaraj)\
**Post date:** [December 7, 2023, 12:06pm UTC](https://forum.heroiclabs.com/t/findorcreatematch-query/4702/3 "2023-12-07T12:06:02Z")

</div>

Tried from the Unity Client API as well but no luck

```auto
  var result = await _client.ListMatchesAsync(_session, 2, 4, 5, true, string.Empty,
                "+label.gameMode:online_random");

```

---

<div class="post-metadata">

**Author:** ![sesposito](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.heroiclabs.com/sesposito/32/2594_2.png) [@sesposito](https://forum.heroiclabs.com/u/sesposito)\
**Post date:** [December 7, 2023, 12:44pm UTC](https://forum.heroiclabs.com/t/findorcreatematch-query/4702/4 "2023-12-07T12:44:35Z")

</div>

> [@Sathyaraj](#):
>
> `let matchId = nk.matchCreate(online_random, { gameMode: online_random });`

Shouldn’t `online_random` in the label object be a string?

---

<div class="post-metadata">

**Author:** ![Sathyaraj](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.heroiclabs.com/sathyaraj/32/1905_2.png) [@Sathyaraj](https://forum.heroiclabs.com/u/Sathyaraj)\
**Post date:** [December 7, 2023, 1:31pm UTC](https://forum.heroiclabs.com/t/findorcreatematch-query/4702/5 "2023-12-07T13:31:37Z")

</div>

It is a string stored in a const  
const online\_random = “online\_random”;

---

<div class="post-metadata">

**Author:** ![sesposito](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.heroiclabs.com/sesposito/32/2594_2.png) [@sesposito](https://forum.heroiclabs.com/u/sesposito)\
**Post date:** [December 7, 2023, 2:53pm UTC](https://forum.heroiclabs.com/t/findorcreatematch-query/4702/6 "2023-12-07T14:53:31Z")

</div>

Can you please share your `matchInit` function?

---

<div class="post-metadata">

**Author:** ![Sathyaraj](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.heroiclabs.com/sathyaraj/32/1905_2.png) [@Sathyaraj](https://forum.heroiclabs.com/u/Sathyaraj)\
**Post date:** [December 8, 2023, 4:58am UTC](https://forum.heroiclabs.com/t/findorcreatematch-query/4702/7 "2023-12-08T04:58:13Z")

</div>

Figured out the solution. I was returning an empty string instead of an actual label in matchInit  
By the way, can we read the parameters that we used when creating the match in matchInit? I can use the same to return  
return {  
state: initialGameState,  
tickRate: TICK\_RATE, // 1 tick per second = 1 MatchLoop func invocations per second  
label: JSON.stringify({ gameMode: online\_random })  
};

---

<div class="post-metadata">

**Author:** ![Sathyaraj](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.heroiclabs.com/sathyaraj/32/1905_2.png) [@Sathyaraj](https://forum.heroiclabs.com/u/Sathyaraj)\
**Post date:** [December 8, 2023, 5:11am UTC](https://forum.heroiclabs.com/t/findorcreatematch-query/4702/8 "2023-12-08T05:11:43Z")

</div>

After creating the match does the host join automatically or do we need to call join match manually?  
When the player 2 joins the length of the presence is just 1.

const online\_private\_matchJoin = function (ctx: nkruntime.Context, logger: nkruntime.Logger, nk: nkruntime.Nakama, dispatcher: nkruntime.MatchDispatcher, tick: number, state: GameState, presences: nkruntime.Presence): {  
state: GameState  
} | null {  
logger.debug(`online_private_matchJoin --> : state ${JSON.stringify(state)}. Presences length: ${presences.length}`);

```
presences.forEach(function (p) {
    state.presences[p.sessionId] = p;
});

return {
    state
};

```

}

---

<div class="post-metadata">

**Author:** ![Sathyaraj](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.heroiclabs.com/sathyaraj/32/1905_2.png) [@Sathyaraj](https://forum.heroiclabs.com/u/Sathyaraj)\
**Post date:** [December 8, 2023, 5:17am UTC](https://forum.heroiclabs.com/t/findorcreatematch-query/4702/9 "2023-12-08T05:17:04Z")

</div>

And if we are implementing just the authoritative multiplayer do we need to implement these in unity client?  
\_socket.ReceivedMatchPresence += OnMatchPresenceEvent;  
\_socket.ReceivedMatchState += OnReceivedMatchState;

---

<div class="post-metadata">

**Author:** ![sesposito](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.heroiclabs.com/sesposito/32/2594_2.png) [@sesposito](https://forum.heroiclabs.com/u/sesposito)\
**Post date:** [December 11, 2023, 1:37pm UTC](https://forum.heroiclabs.com/t/findorcreatematch-query/4702/10 "2023-12-11T13:37:14Z")

</div>

1. Yes you can store the init params in the match state, match label or a storage object depending on your needs.
2. In an authoritative match the host is the server and each of players has to connect to a match. If you’re using a hybrid authoritative/relayed model the client that will host the match still has to connect itself to the match. You need to ensure you’ve implemented the `matchJoin` and `matchJoinAttempt` handlers correctly. Please refer to the [project template](https://github.com/heroiclabs/nakama-project-template/blob/master/main.ts) for a working example.
3. Yes you still need to handle [match state](https://heroiclabs.com/docs/nakama/concepts/multiplayer/authoritative/#receive-data-messages) messages and listen to presence change events if required.

---

<div class="post-metadata">

**Author:** ![Sathyaraj](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.heroiclabs.com/sathyaraj/32/1905_2.png) [@Sathyaraj](https://forum.heroiclabs.com/u/Sathyaraj)\
**Post date:** [January 10, 2024, 11:13am UTC](https://forum.heroiclabs.com/t/findorcreatematch-query/4702/11 "2024-01-10T11:13:22Z")

</div>

@sesposito When player 2 joins the authoritative server in his device OnMatchPresenceEvent gets fired only his ID gets fired in the parameter. I want to access all players details who joined before him. How can I do that in unity?

---

<div class="post-metadata">

**Author:** ![sesposito](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.heroiclabs.com/sesposito/32/2594_2.png) [@sesposito](https://forum.heroiclabs.com/u/sesposito)\
**Post date:** [January 10, 2024, 11:48am UTC](https://forum.heroiclabs.com/t/findorcreatematch-query/4702/12 "2024-01-10T11:48:15Z")

</div>

The OnMatchPresenceEvent is fired for each join/leave, the client should keep track of this information if it needs to know what players are currently in the match.

---

<div class="post-metadata">

**Author:** ![Sathyaraj](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.heroiclabs.com/sathyaraj/32/1905_2.png) [@Sathyaraj](https://forum.heroiclabs.com/u/Sathyaraj)\
**Post date:** [January 10, 2024, 12:02pm UTC](https://forum.heroiclabs.com/t/findorcreatematch-query/4702/13 "2024-01-10T12:02:06Z")

</div>

@sesposito Correct. When the second player joins. How do I display an UI showing the number of players in the current match. OnMatchPresenceEvent fired with one entry which is player 2. Player 2 has no information about the player 1 who joined earlier

---

<div class="post-metadata">

**Author:** ![sesposito](https://sea2.discourse-cdn.com/flex020/user_avatar/forum.heroiclabs.com/sesposito/32/2594_2.png) [@sesposito](https://forum.heroiclabs.com/u/sesposito)\
**Post date:** [January 10, 2024, 12:18pm UTC](https://forum.heroiclabs.com/t/findorcreatematch-query/4702/14 "2024-01-10T12:18:34Z")

</div>

In your match join handler - when a player joins you can broadcast the current list of players you’re keeping in your match state.
