preface

Nowadays, many companies are focused on the separation of the front end and the back end. This may have a problem, the back-end interface has not been written, we 🐂🐂 front-end students have finished the front-end, urgent interface debugging. In order to solve this problem, I wrote a mock front-end interface platform. The project development time is not long, and the idea is not clear.

Online experience address: Interface Mock platform

Source address: Git source

Train of thought

An interface request contains the request line, request header, and request content. We can parse a request through Node and then match the contents of the interface, returning the data that matches the conditions of the interface request, like a faker. Falsify the data that a real interface would return to make it look like a real interface.

implementation

Functions implemented:

Log in and register 2. Add or delete projects 3. Add or delete interfaces 4Copy the code

Technology stack: nextJS + KOA + SQLite + Sequelize

This project is generally not complicated, and can be used as a demo for students who want to learn the above techniques.

Overall Project Architecture

The project is based on server-side rendering and has two pages: the home page and the project details page. I put the node interface service and the server rendering framework NexJS service on the same port. Can also be separated, here is the main do not want to re-establish a service.

Database using SQlite3, its benefits are embedded, zero configuration, super lightweight, data in the form of file storage, no need to configure additional database. To put it bluntly, it’s convenient, and it’s certainly easy to use.

Database connections are made through the ORM framework sequelize: The framework uses metadata to describe the details of Object Relational Mapping. This is a good thing for those who do not know THE SQL language. You can use this framework to operate ona database without writing SQL statements, just like YOU use JS to operate on objects.

The route design is also very simple. There are three types of routes:

  1. Handles routing for server page rendering,
  2. Handles routing of page requests,
  3. Handles the routing of the mock interface.
// Next page API interface
router.post('/api/:page'.async ctx => {
    await routePost({ params: ctx.params.page, query: ctx.request.body }).then((res, err) = > {
        response(res, err, ctx)
    })
})

router.get('/api/:page'.async ctx => {
    await routeGet({ params: ctx.params.page, query: ctx.request.query }).then((res, err) = > {
        response(res, err, ctx)
    })
})

router.delete('/api/:page'.async ctx => {
    await routeDelete({ params: ctx.params.page, query: ctx.request.body }).then((res, err) = > {
        response(res, err, ctx)
    })
})

// Mock data interface
router.all('/mock/:project_id/*'.async ctx => {
    const { method, body, url, header } = ctx.request
    await routeMock({ params: ctx.params, body, method, url, header }).then((res, err) = > {
        response(res, err, ctx)
    })
})

// Next Page interface
app.prepare()
    .then((a)= > {

        / / home page
        router.get('/'.async ctx => {
            await app.render(ctx.req, ctx.res, '/', ctx.query)
            ctx.respond = false
        })
        / / project
        router.get('/project'.async ctx => {
            await app.render(ctx.req, ctx.res, `/project`, ctx.query)
            ctx.respond = false
        })

        // If you have not configured nginx for static file service, make sure to enable the following code
        router.get(The '*'.async ctx => {
            await handle(ctx.req, ctx.res)
            ctx.respond = false
        })
        // Prevent the console from reporting 404 error
        server.use(async (ctx, next) => {
            ctx.res.statusCode = 200
            await next()
        })
        server.use(router.routes()).use(router.allowedMethods())
        server.listen(port, () => {
            console.log(`> Ready on http://localhost:${port}`)})})Copy the code

The distinction is made by URL: API is the page request, mock is the interface mock request, and the other is the next page rendering request. By determining the url of the request, perform different processing:

routeDelete: async ({ params, query }) => {
        const { id } = query
        switch (params) {
            case 'project':
                await api.deleteApi(id)                     // Clear the API interface when deleting the project
                return await project.deleteOne(id).then(res= > response(0, res)).catch(error= > response(1, error.message))
            case 'interface':
                return await api.deleteOneApi(id).then(res= > response(0, res)).catch(error= > response(1, error.message))
            default:
                return 'Interface request error'}},Copy the code

Similar to the above, please refer to the source code for details.

Overall project process

New Project (project_id)

->

Create an interface (URL, Method, HEADERS, Body, data)

->

Domain name of the local project proxy interface

->

Make a request for the created interface (http://host/mock/project_id/xxxxxx)

->

Koa parses the request to get the parameters (URL, method, body, headers)

->

The request parameter matches the corresponding interface through the route judgment

->

Look up the corresponding data in the interface data table based on project_id and return it to the local project

Projects using

Currently, the mock interface only supports returning JSON data. In the future, I want to add other data formats such as returned arrays, Boolean values, etc.

Use:

  1. You can create your own project with an online address, configure the interface, and use Postman to test whether the interface works.
  2. You can run the service locally through clone source code, and you can also test it through Postman or other tools, just change the service domain name to local.

The latter

This project is a personal project, completely open source, but also to solve the real pain points of development.

The project has just started, has not been put into real use, there must be a lot of problems, and unreasonable place. If you have any questions, please leave a comment.

If you are interested in this project, you can find my contact information here, so that you can participate in this project and continue to do it.