📜  adonis js - Javascript (1)

📅  最后修改于: 2023-12-03 15:29:18.239000             🧑  作者: Mango

Adonis JS - The Modern Node.js Framework

Adonis JS is a powerful and modern Node.js framework for building web and mobile applications. It is designed with developer productivity in mind, making it easy to build secure and scalable applications that run faster and more efficiently.

Features
  • MVC architecture
  • ORM (Object Relational Mapping)
  • Middleware support
  • Request validation
  • Web sockets
  • Jobs and Queues
  • Authentication
  • Authorization
  • Encryption
  • CSRF protection
  • GraphQL support
Getting Started

To start using Adonis JS, you need to have Node.js and npm installed on your computer. Once you have these installed, you can create a new Adonis JS project using the Adonis CLI:

npm i -g @adonisjs/cli
adonis new my-app
cd my-app
adonis serve --dev

This will create a new Adonis JS project called my-app and start the development server. You can then open a browser and navigate to http://localhost:3333 to see your application running.

MVC Architecture

Adonis JS follows the Model-View-Controller (MVC) architecture, which separates the application into three distinct components. This makes it easy to develop complex applications and maintain them over time.

  • Models: This is where you define your data models and business logic.
  • Controllers: This is where you handle incoming requests and provide responses.
  • Views: This is where you display data and interact with the user.
ORM

Adonis JS includes an ORM (Object Relational Mapping) called Lucid, which makes it easy to work with databases. With Lucid, you can define your models and database schema in JavaScript and then use the ORM to perform CRUD operations.

const User = use('App/Models/User')

const user = new User()
user.username = 'john'
user.email = 'john@example.com'
user.password = 'secret'
await user.save()
Middleware

Adonis JS includes middleware support, which allows you to modify incoming requests and outgoing responses. Middleware can be used to add global functionality to your application, such as logging or authentication.

const axios = use('axios')

class LogRequest {
  async handle ({ request }, next) {
    console.log(request.method(), request.url())
    await next()
  }
}

class AddAuthHeader {
  async handle ({ request }, next) {
    request.headers['Authorization'] = `Bearer ${process.env.TOKEN}`
    await next()
  }
}

axios.interceptors.request.use(async (config) => {
  await new AddAuthHeader().handle({ request: config }, async () => {})
  await new LogRequest().handle({ request: config }, async () => {})
  return config
})
Request Validation

Adonis JS includes built-in request validation, making it easy to ensure that incoming requests meet certain criteria before they are processed. You can use the validation middleware to enforce rules such as required fields, maximum length, and email addresses.

class UserValidator {
  get rules () {
    return {
      email: 'required|email|unique:users,email',
      password: 'required|min:6'
    }
  }

  async fails (errorMessages) {
    throw new Error(errorMessages[0].message)
  }
}

Route.post('/register', async ({ request }) => {
  await request.validate(UserValidator)
  const user = new User()
  user.email = request.input('email')
  user.password = await Hash.make(request.input('password'))
  await user.save()
  return { message: 'User registered successfully' }
})
Web Sockets

Adonis JS includes built-in support for Web Sockets, making it easy to build real-time applications. With Web Sockets, you can stream data in real-time between the client and server, without the need for HTTP polling.

const Ws = use('Ws')

Ws.channel('chat:*', ({ channel, auth, socket }) => {
  console.log('user joined channel', channel.topic)
  socket.on('message', (message) => {
    console.log(`${auth.user.username}: ${message}`)
    socket.broadcastToAll('message', { from: auth.user.username, message })
  })
})
Jobs and Queues

Adonis JS includes built-in support for Jobs and Queues, making it easy to perform time-consuming tasks in the background. With Jobs and Queues, you can offload tasks such as sending emails or processing files, to a separate process, freeing up your main application to handle requests.

const Job = use('Job')

class SendEmailJob extends Job {
  static get key () {
    return 'send-email'
  }

  async handle (data) {
    const email = data.email
    const message = data.message
    await Mail.send((message) => {
      message.to(email).from('noreply@example.com').subject('New Message')
      message.html('Hello, World!')
    })
  }
}

await SendEmailJob.dispatch({ email: 'john@example.com', message: 'Hello, World!' })
Authentication

Adonis JS includes built-in support for Authentication, making it easy to secure your application. With Authentication, you can authenticate users using a variety of methods, such as JWT tokens or session-based authentication.

Route.post('/login', async ({ auth, request }) => {
  const email = request.input('email')
  const password = request.input('password')
  const token = await auth.attempt(email, password)
  return { token }
})

Route.get('/dashboard', ({}) => {
  return { message: 'Welcome to the dashboard!' }
}).middleware(['auth'])
Authorization

Adonis JS includes built-in support for Authorization, making it easy to control access to different parts of your application. With Authorization, you can define roles and permissions, and restrict access based on these roles.

class CanEditPost {
  async handle ({ auth, params }, next) {
    const user = await auth.getUser()
    const post = await Post.find(params.id)
    if (user.id !== post.user_id) {
      throw new Error('Unauthorized')
    }
    await next()
  }
}

Route.patch('/posts/:id', ({ auth, params, request }) => {
  await request.validate(PostValidator)
  const post = await Post.find(params.id)
  post.title = request.input('title')
  post.body = request.input('body')
  await post.save()
}).middleware(['auth', 'can:edit-post'])
Encryption

Adonis JS includes built-in support for Encryption, making it easy to encrypt and decrypt data. With Encryption, you can securely store sensitive data such as passwords or credit card numbers.

class UserController {
  async register ({ request, response, crypto }) {
    const user = new User()
    user.email = request.input('email')
    user.password = await crypto.encrypt(request.input('password'))
    await user.save()
    return response.send(user)
  }

  async login ({ request, response, crypto, auth }) {
    const password = request.input('password')
    const user = await User.query().where('email', request.input('email')).firstOrFail()
    if (!await crypto.decrypt(user.password)) {
      throw new Error('Invalid password')
    }
    const token = await auth.attempt(request.input('email'), password)
    return response.send({ token })
  }
}
CSRF Protection

Adonis JS includes built-in support for CSRF (Cross-Site Request Forgery) protection, making it easy to prevent malicious requests. With CSRF protection, you can ensure that requests originate from your application and not from an external source.

class Csurf {
  async handle ({ request, response, session }, next) {
    const token = crypto.randomBytes(16).toString('hex')
    request._csrf = token
    session.put('_csrf', token)
    response.header('X-CSRF-TOKEN', token)
    await next()
  }
}

Route.get('/profile', ({}) => {
  return { message: 'Profile page' }
}).middleware(['csrf'])
GraphQL Support

Adonis JS includes built-in support for GraphQL, making it easy to build GraphQL APIs. With GraphQL, you can define your API using a schema, and then use that schema to generate queries and mutations.

const { buildSchema } = require('graphql')

const schema = buildSchema(`
  type Query {
    hello: String
  }
`)

const root = {
  hello: () => {
    return 'Hello, world!'
  }
}

const server = new ApolloServer({
  schema,
  rootValue: root
})

server.listen().then(({ url }) => {
  console.log(`GraphQL Server ready at ${url}`)
})
Conclusion

Adonis JS is a modern and powerful Node.js framework that includes all the features you need to build web and mobile applications. Whether you are building a simple blog or a complex e-commerce platform, Adonis JS will help you do it faster and more efficiently.