Tumgik
#putting the font-family string in various points of the code
destiel-wings · 1 year
Text
so last night I did a little remodeling and I've been trying to use a google font for the name of my blog, messing around with the html of my page but the fancy font won't show up in the app 😕 does anyone know why and how i can fix that?
11 notes · View notes
marcotrosi · 6 years
Text
Vim - Menus
Our beloved Vim offers some possibilities to create and use menus to execute various kinds of commands. I know the following solutions ...
the menu command family
the confirm function
the insert user completion (completefunc)
I will not bother you with a detailed tutorial. For more information I always recommend the best place to learn about Vim - the integrated help.
:menu
Let's start with the most obvious one, the menu commands. The menu commands can be used to create menus that can be called via GUI (mouse and keyboard) and via ex-mode. A good use-case is to create menus entries for commands that are not needed often, for which a mapping would be a waste of valueable key combinations and which can probably not be remembered anyway as they are used less frequently.
I'll keep it short here and as there are already tutorials out there. And of course the Vim help is the best place to read about it. :h creating-menus
Vim offers several menu commands. Depending on the current Vim mode your menu changes accordingly. Means if you are in normal mode you will see your normal mode menus, in visual mode you can see only the menus that make sense in visual mode, and so on.
Let's say we want to have a command in the menu that removes duplicate lines and keeps only one. We want that in normal mode the command runs for the whole file and that in visual mode, by selecting a range of lines, the command shall run only for the selected lines. We could put the following lines in our vimrc.
nmenu Utils.DelMultDuplLines :%s/^\(.*\)\(\n\1\)\+$/\1/<cr> vmenu Utils.DelMultDuplLines :s/^\(.*\)\(\n\1\)\+$/\1/<cr>
The here used commands are quite simple. After the menu command you see only 2 parameters. First one is the menu path. I say path because by using the period you can nest your menus. Here it is only the command directly under the Utils menu entry. The second parameter is the command to be executed just like you would do from normal mode.
There are 2 special characters that can be used in the first parameter. & and <tab>. & can be used to add a shortcut key to the menu and <tab> to add a right aligned text in the menu. Try it out!
Remember that you can access the menu also via ex-mode.
:menu Utils.DelMultDuplLines
But please don't type all the text and use the tabulator key to do the autocompletion for you. ;-)
confirm()
The confirm function. Luckily I already wrote about this possibility. So instead of copy-pasting the text I just link to it.
vim-confirm-function
set completefunc
Let's get dirty now. I guess the insert completion pop-up menu is well known by everyone. But did you know that you can misuse it for more than just auto-completion? I did not. I will show you what I mean.
Usually the auto-completion is triggered by pressing Ctrl-n, Ctrl-p or Ctrl-x Ctrl-something in insert mode. One of these key mappings is Ctrl-x Ctrl-u which triggers an user specific function. Means we can write a function that does what we want and assign it to the completefunc option. Let's check what we need to consider when writing such a function.
The completefunc you have to write has 2 parameters. And the function gets called twice by Vim. When calling the function the first time, Vim passes the parameters 1 and empty. In this case it is your task to usually find the beginning of the word you want to complete and return the start column. One the second call Vim passes 0 and the word the shall be completed.
function! MyCompleteFunc(findstart, base) if a:findstart " write code to find beginning of the word else " write code to create a list of possible completions end endfunction set completefunc=MyCompleteFunc
For more information and an example check :h complete-functions.
Now let's re-create the LaTeX example using the completefunc. Here is a possible solution that supports nested menus, so for 1 level menus the code can be reduced a lot.
https://gist.github.com/marcotrosi/e2918579bce82613c504e7d1cae2e3c0
Okay let's go through it step by step.
In the beginning you see 2 variables. InitMenu and NextMenu. InitMenu defines the menu entry point and NextMenu remembers the name of the next menu. I just wanted to have nested menus and that's what is this for.
Next is the completefunc we have to write. I called mine LatexFont. As shown before it consists of an if-else-block, where the if-true-block gets the word before the cursor and the else-block will return a list that contains some information. In the simplest form this would only be a list of strings that would be the popup-menu-entries. See the CompleteMonths example from the Vim help. But I added some more information. Let's see what it is.
The basic idea is to have one initial menu and many sub-menus, they are all stored in a single dictionary name menus and are somehow connected and I want to decide which one to return. As I initialized my InitMenu variable with "Font" this must be my entry point. After the declaration of the local menus dictionary you can see an if clause that checks if s:NextMenu is empty. So if s:NextMenu is empty it will be initialized with my init value I defined in the very beginning. And at the end I return one of the menus so that Vim can display it as a popup menu.
Now let's have a closer look at the big dictionary. You can see 4 lists named Font, FontFamily, FontStyle and FontSize. Each list contains the popup-menu entries. I use the key user_data to decide whether I want to attach a sub-menu or if the given menu is the last in the chain. To attach a sub-menu I just provide the name of the menu and when the menu ends there I use the string "_END_". So the restriction is that you can't name a menu "_END_" as it is reserved now. By the way, I didn't try it, but I guess that user_data could be of any datatype and is probably not limited to strings.
Let's see what the other keys contain. There are the keys word, abbr and dup. word contains the string that replaces the word before the cursor, which is also stored in a:base. abbr contains the string that is used for display in the popup-menu. From the insert auto-completion we are used to the word displayed is also the word to be inserted. Luckily Vim can distinguish that. This gives me the possibility to display a menu (like FontFamily, FontStyle, FontSize) but at the same time keeping the original unchanged word before the cursor. This is basically the whole trick. Plus the additional user_data key that allows me to store any kind of information for re-use and decisions. With the dup key I tell Vim to display also duplicate entries. For more information on supported keys check :h complete-items.
Now let's get to the rest of the nested menu implementation. Imagine you have selected an entry of the initial menu. You confirm by pressing SPACE and now I want to open the sub-menu automatically. To achieve that I use a Vim event named CompleteDone which triggers my LatexFontContinue function, and the CompleteDone event is triggered when closing the popup menu either by selecting a menu entry or by aborting. Within that function I decide whether to trigger the user completion again or to quit. Beside the CompleteDone event Vim also has a variable named v:completed_item that contains a dictionary with the information about the selected menu item. The first thing I do is saving the user_data value in a function local variable.
let l:NextMenu = get(v:completed_item, 'user_data', '')
The last parameter is the default value for the get function and is an empty string just in case the user aborted the popup-menu in which case no user_data would be available.
One more info - this line ...
inoremap <expr><esc> pumvisible() ? "\<c-e>" : "\<esc>"
... allows the user to abort the menu by pressing the ESC key intead of Ctrl-e.
And last but not least the if clause that either sets the script variable s:NextMenu to empty string when the local l:NextMenu is empty or "_END_" and quits the function without doing anything else, or the else branch that stores the next menu string in s:NextMenu and re-triggers the user completion.
The rest of the file is self-explanatory.
I'm sure we can change the code a bit to execute also other command types, e.g. by storing a command as a string and executing it.
Let me know what you did with it.
2 notes · View notes
mbaljeetsingh · 7 years
Text
How to Get Started With restdb.io and Create a Simple CMS
This article was sponsored by restdb.io. Thank you for supporting the partners who make SitePoint possible.
Databases strike fear into the heart of the most experienced developers. Installation, updates, disk space provision, back-ups, efficient indexing, optimized queries, and scaling are problems most could do without. Larger organizations will employ a knowledgeable dev ops person who dedicates their life to the database discords. Yet the system inevitably fails the moment they go on vacation.
A more practical option is to outsource your database and that's exactly the service restdb.io provides. They manage the tricky data storage shenanigans, leaving you to concentrate on more urgent development tasks.
restdb.io: the Basics
restdb.io is a plug and play cloud NoSQL database. It will be immediately familiar to anyone with MongoDB experience. The primary differences:
there's no need to manage your installation, storage or backups
you can define a data structure schema in restdb.io
data fields can have relationships with other fields in other collections
there's no need to define indexes
data can be queried and updated through a REST API authenticated by HTTP or Auth0/JWT tokens
queries and updates are sent and received in JSON format
there are tools to enter, view and export data in various formats
it supports some interesting bonus features such as codehooks, email, web form generation, websites, realtime messaging, and more.
A free account allows you to assess the service with no obligation. Paid plans offer additional storage space, query throughput, developer accounts and MongoDB integration.
In the following sections I'll describe how to:
configure a new database and enter data
use that data to render a set web pages hosted on restdb.io, and
use the API to provide a search facility for content editors.
Step 1: Create a New Database
After signing up with a Google, Facebook or email account, you can create a new empty database. This generates a new API endpoint URL at yourdbname.restdb.io:
Step 2: Create a New Collection
A database contains one or more collections for storing data. These are analogous to SQL database tables. Collections contain "documents" which are analogous to SQL database records (table rows).
The restdb.io interface offers two modes:
Standard mode shows the available collections and allows you to insert and modify data.
Developer mode allows you to create and configure collections.
Enter Developer Mode (top-right of screen) and click the Add Collection button.
A collection requires a unique name (I've used "content") and an optional description and icon. Hit Save to return to your database overview. The "content" collection will appear in the list along with several other non-editable system collections.
Alternatively, data can be imported from Excel, CSV or JSON files to create a collection by hitting Import in the standard view.
Step 3: Define Fields
Staying in Developer Mode, click the "content" collection and choose the Fields tab. Click Add Fields to add and configure new fields which classify the data in the collection.
Each collection document will sore data about a single page in the database-driven website. I've added five fields:
slug - a text field for the page path URL
title - a text field for the page title
body - a special markdown text field for the page content
image - a special image field which permits any number of uploaded images (which are also stored on the restdb.io system)
published - boolean value which must be true for pages to be publicly visible.
Step 4: Add Documents
Documents can be added to a collection in either standard or developer mode (or via the API). Create a few documents with typical page content:
The slug should be empty for the home page.
Step 5: Create a Database-Driven Website (Optional)
restdb.io provides an interesting feature which can create and host a database-driven website using data documents in a collection.
The site is hosted at www-yourdbname.restdb.io but you can point any domain at the pages. For instructions, click Settings from the Database list or at the bottom of the left-hand panel then click the Webhosting tab.
To create the website, Pages must be configured in Developer Mode which define templates to view the content. Templates contain a code snippet which sets:
the context - a query which locates the correct document in a collection, and
the HTML - a structure which uses handlebars template syntax to insert content into appropriate elements.
Click Add Page to create a page. Name it the special name /:slug - this means the template will apply to any URL other than the home page (which does not have a slug). Hit Save and return to the page list, then click the /:slug entry to edit.
Switch to the Settings tab and ensure text/html is entered as the Content Type and Publish is checked before hitting Update:
Now switch to the Code for "/:slug" tab. Enter the context code at the top of the editor:
{ "docs": { "collection": "content", "query": { "slug": "", "published": true } } }
This defines a query so the template can access a specific document from our content collection. In this case, we're fetching the published document which matches the slug passed on the URL.
All restdb.io queries return an array of objects. If no document is returned, the docs array will be empty so we can add code to return that the page is not available immediately below the context:
<!doctype html> <html> <body> <h1>Page not available</h1> <p>Sorry, this page cannot be viewed. Please return later.</p> </body> </html>
Below this, we can code the template which slots the title, body and image fields into appropriate HTML elements:
<html> <head> <meta charset="utf-8"> <title></title> <meta name="viewport" content="width=device-width,initial-scale=1"> <style> body { font-family: sans-serif; font-size: 100%; color: #333; background-color: #fff; max-width: 40em; padding: 0 2em; margin: 1em auto; } </style> </head> <body> <header> <img src="http://ift.tt/2wysXbS; alt="image" /> <h1></h1> </header> <main> <p><a href="/">Return to the home page...</a></p> </main> </body> </html>
Note our markdown body field must be rendered with a markdown handler.
Save the code with Ctrl|Cmd + S or by returning to the Settings tab and hitting Update.
The /:slug page template will apply to all our content collection — except for the home page, because that does not have a slug! To render the home page, create a New Page with the name home with identical settings and content. You may want to tweak the template for home-page-specific content.
Once saved, you can access your site from https://www-yourdbname.restdb.io/. I've created a very simple three-page site at http://ift.tt/2ut9U5n.
For more information about restdb.io page hosting, refer to:
Pages and Database Driven Website Hosting
The restdb.io Dynamic Website Demo
handlebar template syntax
Step 6: API Queries
Creating a site to display your data may be useful, but you'll eventually want to build an application which queries and manipulates information.
restdb.io's REST API provides endpoints controlled via HTTP:
HTTP GET requests retrieve data from a collection
HTTP POST requests create new documents in a collection
HTTP PUT requests update documents in a collection
HTTP PATCH requests update one or more properties in a document in a collection
HTTP DELETE requests delete documents from a collection
There are a number of APIs for handling uploaded media files, database meta data and mail but the one you'll use most often is for collections. The API URL is:
https://yourdbname.restdb.io/rest/collection-name/
The URL for my "content" collection is therefore:
http://ift.tt/2uKFM0F
Queries are passed to this URL as a JSON-encoded querystring parameter named q, e.g. fetch all published articles in the collection:
http://ift.tt/2vnljTf;: true}
However, this query will fail without an API key passed in the x-apikey HTTP header. A full-access API key is provided by default but it's advisable to create keys which are limited to specific actions. From the database Settings, API tab:
Click Add New to create a new key. The one I created here is limited to GET (query) requests on the content collection only. You should create a similarly restricted key if you will be using client-side JavaScript Ajax code since the string will be visible in the code.
It's now possible to build a standalone JavaScript query handler (ES5 has been used to ensure cross-browser compatibility without a pre-compile step!):
// restdb.io query handler var restDB = (function() { // configure for your own DB var api = 'http://ift.tt/2uKGivH', APIkey = '597dd2c7a63f5e835a5df8c4'; // query the database function query(url, callback) { var timeout, xhr = new XMLHttpRequest(); // set URL and headers xhr.open('GET', api + url); xhr.setRequestHeader('x-apikey', APIkey); xhr.setRequestHeader('content-type', 'application/json'); xhr.setRequestHeader('cache-control', 'no-cache'); // response handler xhr.onreadystatechange = function() { if (xhr.readyState !== 4) return; var err = (xhr.status !== 200), data = null; clearTimeout(timeout); if (!err) { try { data = JSON.parse(xhr.response); } catch(e) { err = true; data = xhr.response || null; } } callback(err, data); }; // timeout timeout = setTimeout(function() { xhr.abort(); callback(true, null); }, 10000); // start call xhr.send(); } // public query method return { query: query }; })();
This code passes queries to the restdb.io API endpoint and sets the appropriate HTTP headers including x-apikey for the API key. It times out if the response takes longer than ten seconds. A callback function is passed an error and any returned data as a native object. For example:
// run a query restDB.query( '/content?q={"published":true}', function(err, data) { // success! if (!err) console.log(data); } );
The console will output an array of documents from the content collection, e.g.
[ { _id: "1111111111111111", slug: "", title: "Home page", body: "page content...", image: [], published: true }, { _id: "22222222222222222", slug: "page-two", title: "Page Two", body: "page content...", image: [], published: true }, { _id: "33333333333333333", slug: "page-three", title: "Another page", body: "page content...", image: [], published: true } ]
The API can be called from any language which can make an HTTP request. restdb.io provides examples for cURL, jQuery $.ajax, JavaScript XMLHttpRequest, NodeJS, Python, PHP, Java, C#, Objective-C and Swift.
I've created a simple example at Codepen.io which allows you to search for strings in the title and body fields and displays the results:
See the Pen restdb.io query by SitePoint (@SitePoint) on CodePen.
It passes the following query:
{ "$or": [ { "title": {"$regex": "searchstring"} }, { "body": {"$regex": "searchstring"} } ]}
where searchstring is the search text entered by the user.
An additional h querystring parameter limits the returned fields to just the slug, title and published flag:
{ "$fields": { "slug": 1, "title": 1, "published": 1 } }
Further information:
Querying with the API
Code examples for REST API
Step 7: Build Your Own CMS
A few steps were required to create a database-driven website and a simple search facility. You could edit pages directly using restdb.io's user interface but it would be possible to build a bespoke CMS to manipulate the content. It would require:
A new restdb.io API key (or change the existing one) to have appropriate GET, POST, PUT, PATCH and DELETE access to the content collection.
A user interface to browse or search for pages (the one above could be a good starting point).
A process to start a new page or GET existing content and place it in an editable form.
Processes to add, update or delete pages using the appropriate HTTP methods.
The editing system should run on a restricted device or behind a login to ensure only authenticated users can access. Take care not to reveal your restdb.io API key if using client-side code!
Further information:
Data manipulation with REST
Code examples for REST API
Try restdb.io Today!
This article uses restdb.io to build a rudimentary CMS, but the service is suitable for any project which requires data storage. The REST API can be accessed from any language or framework which makes it ideal for applications with multiple interfaces, e.g. a web and native mobile view.
restdb.io provides a practical alternative to managing your own database software installation. It's simple to use, fast, powerful, highly scalable and considerably less expensive than hiring a database expert! Your application hosting costs will also reduce since all data is securely stored and backed-up on the restdb.io servers.
Finally, restdb.io makes you more productive. You can concentrate on the main application because data storage no longer causes concerns for you and your team.
Start building your restdb.io database today and let us know how you get on!
Continue reading %How to Get Started With restdb.io and Create a Simple CMS%
via SitePoint http://ift.tt/2uudPLd
0 notes
t-baba · 7 years
Photo
Tumblr media
How to Get Started With restdb.io and Create a Simple CMS
This article was sponsored by restdb.io. Thank you for supporting the partners who make SitePoint possible.
Databases strike fear into the heart of the most experienced developers. Installation, updates, disk space provision, back-ups, efficient indexing, optimized queries, and scaling are problems most could do without. Larger organizations will employ a knowledgeable dev ops person who dedicates their life to the database discords. Yet the system inevitably fails the moment they go on vacation.
A more practical option is to outsource your database and that's exactly the service restdb.io provides. They manage the tricky data storage shenanigans, leaving you to concentrate on more urgent development tasks.
restdb.io: the Basics
restdb.io is a plug and play cloud NoSQL database. It will be immediately familiar to anyone with MongoDB experience. The primary differences:
there's no need to manage your installation, storage or backups
you can define a data structure schema in restdb.io
data fields can have relationships with other fields in other collections
there's no need to define indexes
data can be queried and updated through a REST API authenticated by HTTP or Auth0/JWT tokens
queries and updates are sent and received in JSON format
there are tools to enter, view and export data in various formats
it supports some interesting bonus features such as codehooks, email, web form generation, websites, realtime messaging, and more.
A free account allows you to assess the service with no obligation. Paid plans offer additional storage space, query throughput, developer accounts and MongoDB integration.
In the following sections I'll describe how to:
configure a new database and enter data
use that data to render a set web pages hosted on restdb.io, and
use the API to provide a search facility for content editors.
Step 1: Create a New Database
After signing up with a Google, Facebook or email account, you can create a new empty database. This generates a new API endpoint URL at yourdbname.restdb.io:
Step 2: Create a New Collection
A database contains one or more collections for storing data. These are analogous to SQL database tables. Collections contain "documents" which are analogous to SQL database records (table rows).
The restdb.io interface offers two modes:
Standard mode shows the available collections and allows you to insert and modify data.
Developer mode allows you to create and configure collections.
Enter Developer Mode (top-right of screen) and click the Add Collection button.
A collection requires a unique name (I've used "content") and an optional description and icon. Hit Save to return to your database overview. The "content" collection will appear in the list along with several other non-editable system collections.
Alternatively, data can be imported from Excel, CSV or JSON files to create a collection by hitting Import in the standard view.
Step 3: Define Fields
Staying in Developer Mode, click the "content" collection and choose the Fields tab. Click Add Fields to add and configure new fields which classify the data in the collection.
Each collection document will sore data about a single page in the database-driven website. I've added five fields:
slug - a text field for the page path URL
title - a text field for the page title
body - a special markdown text field for the page content
image - a special image field which permits any number of uploaded images (which are also stored on the restdb.io system)
published - boolean value which must be true for pages to be publicly visible.
Step 4: Add Documents
Documents can be added to a collection in either standard or developer mode (or via the API). Create a few documents with typical page content:
The slug should be empty for the home page.
Step 5: Create a Database-Driven Website (Optional)
restdb.io provides an interesting feature which can create and host a database-driven website using data documents in a collection.
The site is hosted at www-yourdbname.restdb.io but you can point any domain at the pages. For instructions, click Settings from the Database list or at the bottom of the left-hand panel then click the Webhosting tab.
To create the website, Pages must be configured in Developer Mode which define templates to view the content. Templates contain a code snippet which sets:
the context - a query which locates the correct document in a collection, and
the HTML - a structure which uses handlebars template syntax to insert content into appropriate elements.
Click Add Page to create a page. Name it the special name /:slug - this means the template will apply to any URL other than the home page (which does not have a slug). Hit Save and return to the page list, then click the /:slug entry to edit.
Switch to the Settings tab and ensure text/html is entered as the Content Type and Publish is checked before hitting Update:
Now switch to the Code for "/:slug" tab. Enter the context code at the top of the editor:
{ "docs": { "collection": "content", "query": { "slug": "", "published": true } } }
This defines a query so the template can access a specific document from our content collection. In this case, we're fetching the published document which matches the slug passed on the URL.
All restdb.io queries return an array of objects. If no document is returned, the docs array will be empty so we can add code to return that the page is not available immediately below the context:
<!doctype html> <html> <body> <h1>Page not available</h1> <p>Sorry, this page cannot be viewed. Please return later.</p> </body> </html>
Below this, we can code the template which slots the title, body and image fields into appropriate HTML elements:
<html> <head> <meta charset="utf-8"> <title></title> <meta name="viewport" content="width=device-width,initial-scale=1"> <style> body { font-family: sans-serif; font-size: 100%; color: #333; background-color: #fff; max-width: 40em; padding: 0 2em; margin: 1em auto; } </style> </head> <body> <header> <img src="http://ift.tt/2uKONXr}}" alt="image" /> <h1></h1> </header> <main> <p><a href="/">Return to the home page...</a></p> </main> </body> </html>
Note our markdown body field must be rendered with a markdown handler.
Save the code with Ctrl|Cmd + S or by returning to the Settings tab and hitting Update.
The /:slug page template will apply to all our content collection — except for the home page, because that does not have a slug! To render the home page, create a New Page with the name home with identical settings and content. You may want to tweak the template for home-page-specific content.
Once saved, you can access your site from https://www-yourdbname.restdb.io/. I've created a very simple three-page site at http://ift.tt/2ut9U5n.
For more information about restdb.io page hosting, refer to:
Pages and Database Driven Website Hosting
The restdb.io Dynamic Website Demo
handlebar template syntax
Step 6: API Queries
Creating a site to display your data may be useful, but you'll eventually want to build an application which queries and manipulates information.
restdb.io's REST API provides endpoints controlled via HTTP:
HTTP GET requests retrieve data from a collection
HTTP POST requests create new documents in a collection
HTTP PUT requests update documents in a collection
HTTP PATCH requests update one or more properties in a document in a collection
HTTP DELETE requests delete documents from a collection
There are a number of APIs for handling uploaded media files, database meta data and mail but the one you'll use most often is for collections. The API URL is:
https://yourdbname.restdb.io/rest/collection-name/
The URL for my "content" collection is therefore:
http://ift.tt/2uKFM0F
Queries are passed to this URL as a JSON-encoded querystring parameter named q, e.g. fetch all published articles in the collection:
http://ift.tt/2usudjk{"published": true}
However, this query will fail without an API key passed in the x-apikey HTTP header. A full-access API key is provided by default but it's advisable to create keys which are limited to specific actions. From the database Settings, API tab:
Click Add New to create a new key. The one I created here is limited to GET (query) requests on the content collection only. You should create a similarly restricted key if you will be using client-side JavaScript Ajax code since the string will be visible in the code.
It's now possible to build a standalone JavaScript query handler (ES5 has been used to ensure cross-browser compatibility without a pre-compile step!):
// restdb.io query handler var restDB = (function() { // configure for your own DB var api = 'http://ift.tt/2uKGivH', APIkey = '597dd2c7a63f5e835a5df8c4'; // query the database function query(url, callback) { var timeout, xhr = new XMLHttpRequest(); // set URL and headers xhr.open('GET', api + url); xhr.setRequestHeader('x-apikey', APIkey); xhr.setRequestHeader('content-type', 'application/json'); xhr.setRequestHeader('cache-control', 'no-cache'); // response handler xhr.onreadystatechange = function() { if (xhr.readyState !== 4) return; var err = (xhr.status !== 200), data = null; clearTimeout(timeout); if (!err) { try { data = JSON.parse(xhr.response); } catch(e) { err = true; data = xhr.response || null; } } callback(err, data); }; // timeout timeout = setTimeout(function() { xhr.abort(); callback(true, null); }, 10000); // start call xhr.send(); } // public query method return { query: query }; })();
This code passes queries to the restdb.io API endpoint and sets the appropriate HTTP headers including x-apikey for the API key. It times out if the response takes longer than ten seconds. A callback function is passed an error and any returned data as a native object. For example:
// run a query restDB.query( '/content?q={"published":true}', function(err, data) { // success! if (!err) console.log(data); } );
The console will output an array of documents from the content collection, e.g.
[ { _id: "1111111111111111", slug: "", title: "Home page", body: "page content...", image: [], published: true }, { _id: "22222222222222222", slug: "page-two", title: "Page Two", body: "page content...", image: [], published: true }, { _id: "33333333333333333", slug: "page-three", title: "Another page", body: "page content...", image: [], published: true } ]
The API can be called from any language which can make an HTTP request. restdb.io provides examples for cURL, jQuery $.ajax, JavaScript XMLHttpRequest, NodeJS, Python, PHP, Java, C#, Objective-C and Swift.
I've created a simple example at Codepen.io which allows you to search for strings in the title and body fields and displays the results:
See the Pen restdb.io query by SitePoint (@SitePoint) on CodePen.
It passes the following query:
{ "$or": [ { "title": {"$regex": "searchstring"} }, { "body": {"$regex": "searchstring"} } ]}
where searchstring is the search text entered by the user.
An additional h querystring parameter limits the returned fields to just the slug, title and published flag:
{ "$fields": { "slug": 1, "title": 1, "published": 1 } }
Further information:
Querying with the API
Code examples for REST API
Step 7: Build Your Own CMS
A few steps were required to create a database-driven website and a simple search facility. You could edit pages directly using restdb.io's user interface but it would be possible to build a bespoke CMS to manipulate the content. It would require:
A new restdb.io API key (or change the existing one) to have appropriate GET, POST, PUT, PATCH and DELETE access to the content collection.
A user interface to browse or search for pages (the one above could be a good starting point).
A process to start a new page or GET existing content and place it in an editable form.
Processes to add, update or delete pages using the appropriate HTTP methods.
The editing system should run on a restricted device or behind a login to ensure only authenticated users can access. Take care not to reveal your restdb.io API key if using client-side code!
Further information:
Data manipulation with REST
Code examples for REST API
Try restdb.io Today!
This article uses restdb.io to build a rudimentary CMS, but the service is suitable for any project which requires data storage. The REST API can be accessed from any language or framework which makes it ideal for applications with multiple interfaces, e.g. a web and native mobile view.
restdb.io provides a practical alternative to managing your own database software installation. It's simple to use, fast, powerful, highly scalable and considerably less expensive than hiring a database expert! Your application hosting costs will also reduce since all data is securely stored and backed-up on the restdb.io servers.
Finally, restdb.io makes you more productive. You can concentrate on the main application because data storage no longer causes concerns for you and your team.
Start building your restdb.io database today and let us know how you get on!
Continue reading %How to Get Started With restdb.io and Create a Simple CMS%
by Craig Buckler via SitePoint http://ift.tt/2hOHQDK
0 notes