Introduction to Keystone
KeystoneJS is an open-source framework for developing database-driven websites, applications, and APIs in Node.js. It provides an easy-to-use Admin UI that handles data persistence through MongoDB or PostgreSQL. The framework is built on Express and offers integration with various authentication systems, including OAuth, Password, and more.
Keystone APIs Explained with Examples
The Keystone API offers a range of functionalities to streamline the development process. Below are some examples of commonly used APIs in KeystoneJS:
Create a New List
To create a new list in Keystone:
const { Keystone } = require('@keystonejs/keystone'); const { MongoAdapter } = require('@keystonejs/adapter-mongoose'); const { Text } = require('@keystonejs/fields'); const keystone = new Keystone({ adapter: new MongoAdapter({ mongoUri: 'mongodb://localhost/my-database' }), }); keystone.createList('Post', { fields: { title: { type: Text }, content: { type: Text }, }, });
Adding Authentication
Keystone provides built-in support for various authentication mechanisms:
const { PasswordAuthStrategy } = require('@keystonejs/auth-password'); const authStrategy = keystone.createAuthStrategy({ type: PasswordAuthStrategy, list: 'User', });
Using GraphQL API
Keystone comes with GraphQL API by default, making it easy to query data:
const query = ` query { allPosts { title content } } `; const result = await keystone.executeQuery(query); console.log(result);
File Upload Handling
Keystone’s file handling API makes it simple to upload and manage files:
const { File } = require('@keystonejs/fields'); keystone.createList('FileUpload', { fields: { file: { type: File }, }, });
Sample Application Using Keystone APIs
Let’s build a sample blog application using Keystone:
const { Text, Slug, DateTime, File, Relationship } = require('@keystonejs/fields'); keystone.createList('User', { fields: { name: { type: Text }, email: { type: Text, isUnique: true }, password: { type: Password }, }, }); keystone.createList('Post', { fields: { title: { type: Text }, slug: { type: Slug, from: 'title' }, content: { type: Text }, postedAt: { type: DateTime }, author: { type: Relationship, ref: 'User' }, }, }); keystone.createList('Comment', { fields: { post: { type: Relationship, ref: 'Post' }, author: { type: Relationship, ref: 'User' }, content: { type: Text }, postedAt: { type: DateTime }, }, });
This basic example sets up three lists: Users, Posts, and Comments. Each list defines its own fields and relationships, facilitating a simple yet powerful blog application.
For detailed documentation, best practices, and advanced configurations, visit the official KeystoneJS website.
Hash: 4cc7a4b341d8ce3315ea112ebb01e664bd328e88781db0f4bbc0e3f65e201bf9