Most efficient way to do simple Entity API queries by node id and content type? A very basic 8.x API question.

What is the approved/simplest methods of confirming a node matching a certain content type and ID exists, and then loading it as an object?

(Use case: a module which accepts a node ID in the URL, that needs to be checked.)

Currently I have:

$node = \Drupal::entityTypeManager()-&gt;getStorage('node')-&gt;load(123);

if ($node-&gt;getType() == 'application') {
  return $node;
} else {
  return false;
}


My first attempt was in reserve (longer/less efficient):

$nids = \Drupal::entityQuery('node')
  -&gt;condition('type', 'application')
  -&gt;condition('nid', 123)
  -&gt;execute();

// followed by entityTypeManager()-&gt;getStorage('node') etc.


But I was wondering if there was a way to make entityQueue() return a flat array of IDs rather than an associative [1=&gt;1,2=&gt;2,3=&gt;3] which you then have to mess around with.
I don't know how your module URL/API is structured, but if your module route has something like myapi/foo/bar/(id) to return a node object, you could upcast it instead. Here is an example from the node module:

entity.node.version_history:
  path: '/node/{node}/revisions'
  defaults:
    _title: 'Revisions'
    _controller: '\Drupal\node\Controller\NodeController::revisionOverview'
  requirements:
    node: \d+


{node} will be upcast to a node object and available in the incoming request to the receiving class.

See: https://www.drupal.org/docs/8/api/routing-system/using-parameters-in-routes

So when you pass that to the receiving method:

use Drupal\node\NodeInterface;

class ExampleController {
  public function foo(NodeInterface $node) {
    if ($node-&gt;getType() != 'application') {
      // do something, throw Exception, etc?
    } 

    // Otherwise this node is an application type.
    return $node;
  }
}


There may be a way to expand on this in the route definition, so you can upcast the node and ensure it is a specific type before doing anything else, eliminating the checking in the method - but I am not sure.

Perhaps:


https://symfony.com/doc/3.4/routing/requirements.html
https://symfony.com/doc/3.4/routing/conditions.html