Skip to content

Commit b80fcd4

Browse files
committed
Adding /api/router/% to allow API queries via path aliases.
1 parent 2c52be1 commit b80fcd4

File tree

3 files changed

+52
-2
lines changed

3 files changed

+52
-2
lines changed

headless.module

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
<?php
22
/**
3-
* big module
3+
* Headless allows you to use Backdrop CMS as an API.
44
*/
55
function headless_menu() {
66
$items = array();
@@ -35,7 +35,17 @@ function headless_menu() {
3535
'page callback' => 'backdrop_get_form',
3636
'page arguments' => array('headless_settings_form'),
3737
'access arguments' => array('administer site configuration'),
38-
'file' => 'headless.admin.inc',
38+
'file' => 'includes/headless.admin.inc',
39+
);
40+
41+
// Router: allow API queries via string paths.
42+
$items['api/router/%'] = array(
43+
'title' => 'Headless router',
44+
'description' => 'Allow queries via string like /api/my-node-title',
45+
'page callback' => 'headless_router',
46+
'page arguments' => array(2),
47+
'access callback' => TRUE,
48+
'file' => 'includes/headless.router.inc',
3949
);
4050

4151
return $items;
File renamed without changes.

includes/headless.router.inc

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
<?php
2+
/**
3+
* Router: allow API queries via strings in URL path.
4+
* The router will try to resolve a string to an API asset.
5+
*/
6+
7+
/**
8+
* Resolve a string path to an API asset.
9+
*
10+
* @param string $path
11+
* The string to try to resolve to an API asset (usually a path).
12+
*/
13+
function headless_router(string $path) {
14+
$path = filter_xss($path);
15+
$assets = [];
16+
$query = db_select('url_alias', 'u')
17+
->fields('u', ['source'])
18+
->condition('alias', '%' . db_like($path) . '%', 'LIKE')
19+
->addTag('node_access')
20+
->execute();
21+
foreach($query as $i => $asset) {
22+
$assets[] = $asset;
23+
}
24+
$source = $assets[0]->source;
25+
$source = explode('/', $source);
26+
if ($source[0] == 'node') {
27+
$node = node_load($source[1]);
28+
$type = $node->type;
29+
headless_type($type, $source[1]);
30+
}
31+
elseif ($source[0] == 'taxonomy') {
32+
$term = taxonomy_term_load($source[2]);
33+
headless_term_item($term->vocabulary, $source[2]);
34+
}
35+
else {
36+
$error = ['code' => 404];
37+
backdrop_json_output($error);
38+
backdrop_exit();
39+
}
40+
}

0 commit comments

Comments
 (0)