Skip to content
This repository has been archived by the owner on Jan 18, 2023. It is now read-only.

Commit

Permalink
Merge pull request #30 from ludicrousxyz/docs
Browse files Browse the repository at this point in the history
Update Docs
  • Loading branch information
nahtnam committed Aug 29, 2019
2 parents 6594b7f + e10ccda commit 7feaa30
Show file tree
Hide file tree
Showing 19 changed files with 159 additions and 151 deletions.
14 changes: 7 additions & 7 deletions docs/server.md
Expand Up @@ -3,9 +3,9 @@ title: server
subtitle: a function to generate a http server and router
---

## `server({ routes, log }): object`
## `server({ routes, opts }): object`

`server` is a function used to take in a path to a set of routes, generate the router, and return a http server and the respective router object (generated by [find-my-way](https://github.com/delvedor/find-my-way)).
`server` is a function used to take in a path to a set of routes or the code to the routes themselves, generate the router, and return a http server and the respective router object (generated by [find-my-way](https://github.com/delvedor/find-my-way)).

### Output

Expand Down Expand Up @@ -33,14 +33,14 @@ This function take an object with a `routes` and `log` property.
```js
{
routes,
log,
opts,
}
```

#### `routes: string[] | string`
#### `routes: string | Route[]`

An array of strings or a string containing paths to folders or single files. You may mix and match files and folders.
A string or an array of routes containing the path to folders or the code itself.

#### `log: boolean`
#### `opts: object`

A boolean to toggle logging to the console.
A hash of options to be sent to the Route class.
2 changes: 1 addition & 1 deletion guides/deployments/netlify.md
Expand Up @@ -15,7 +15,7 @@ This guide assumes that you have already set up a Netlify account, and a GitHub

Before you can deploy, you must first populate your git repository. Follow the [getting started](/guides/getting-started) guide to build you initial app, and verify everything is working with `npm run dev`. Once you have that set up, add a `netlify.toml` file that contains the path to the routes directory.

```toml
```txt
[build]
command = "npm install"
functions = "routes"
Expand Down
3 changes: 2 additions & 1 deletion guides/deployments/now.md
Expand Up @@ -23,7 +23,8 @@ All data required to host on the now platform is stored in a `now.json` file.
{ "src": "/(.*)", "dest": "routes/$1.js" }
],
"env": {
"NODE_ENV": "production"
"NODE_ENV": "production",
"LIGHT_ENV": "now"
}
}
```
Expand Down
17 changes: 9 additions & 8 deletions guides/deployments/runkit.md
Expand Up @@ -12,20 +12,21 @@ RunKit is a fun and dynamic website which lets you prototype your applications.
Simply create a new notebook and add the following code.

```js
const light = require('light');
const { light, Route } = require('light');

process.env.LIGHT_ENVIRONMENT = 'runkit';
process.env.LIGHT_ENV = 'runkit';

module.exports = light({
path: '/',
async handler(req, res) {
class Index extends Route {
async handler() {
return {
hello: 'world',
};
},
});
}
}

module.exports = light(Index);
```

Then click the "run" button. It should print something like `Object {endpoint: function()}`. If you get that, then you are all set. Press the little "endpoint" button underneath the notebook title to see your project live.
Then click the "run" button. It should print `Object {endpoint: function()}`. If you get that, then you are all set. Press the little "endpoint" button underneath the notebook title to see your project live.

A demo of this functionality can be seen on the [home page](/).
17 changes: 8 additions & 9 deletions guides/error-handling.md
Expand Up @@ -12,17 +12,16 @@ Error handling is done mostly by throwing a new Error. Each route is wrapped wit
Simply import [`createError`](/docs/boom/create-error) and throw it at any point. createError will create a boom error resulting in a pretty JSON output.

```js
const { light, createError } = require('light');
const { light, Route, createError } = require('light');

module.exports = light({
path: '/',
async handler(req, res) {
class Index extends Route {
async handler() {
throw createError(401, 'sorry, you cannot access this route');
return {
hello: 'world',
};
},
});
return 'it will not get to me :(';
}
}

module.exports = light(Index);
```

This will result in JSON which looks like this:
Expand Down
11 changes: 6 additions & 5 deletions guides/getting-started.md
Expand Up @@ -38,16 +38,17 @@ Once you've installed light, all `.js` files under the `routes` folder will be u
To get started, populate `routes/index.js`.

```js
const light = require('light');
const { light, Route } = require('light');

module.exports = light({
path: '/',
class Index extends Route {
async handler() {
return {
hello: 'world',
};
},
});
}
}

module.exports = light(Index);
```

Run `npm run dev` to start the development server. You should see an output in your terminal similar to the one below.
Expand Down
2 changes: 1 addition & 1 deletion guides/guides.json
@@ -1,7 +1,7 @@
{
"Getting Started": "getting-started",
"Server vs Serverless": "server-vs-serverless",
"Handler": "handler",
"Routes": "routes",
"Routing": "routing",
"Methods": "methods",
"Params": "params",
Expand Down
47 changes: 0 additions & 47 deletions guides/handler.md

This file was deleted.

2 changes: 2 additions & 0 deletions guides/methods.md
Expand Up @@ -5,6 +5,8 @@ subtitle: respond to custom methods when in server mode

**Please note that methods are environment specific. The details documented below only apply to [server mode](/guides/server-vs-serverless#server) since serverless environment will have their own method handling**

## THIS DOC IS INCOMPLETE. IT WILL BE UPDATED WHEN ROUTING IS UPDATED

## Introduction

Under the hood, light uses [find-my-way](https://github.com/delvedor/find-my-way) to route in server mode. find-my-way supports the following HTTP methods:
Expand Down
20 changes: 12 additions & 8 deletions guides/middleware.md
Expand Up @@ -25,17 +25,21 @@ const checkAuth = async (req, res) => {
To include middleware in your route, simply add it as a property array.

```js
const light = require('light');
const { light, Route } = require('light');

module.exports = light({
path: '/protected',
middleware: [ checkAuth ], // you can have multiple middleware
async handler(req) {
class Index extends Route {
get middleware() {
return [ checkAuth ]; // you can have multiple middleware
}

async handler() {
return {
isAuthenticated: req.isAuthenticated,
isAuthenticated: this.req.isAuthenticated,
};
},
});
}
}

module.exports = light(Index);
```

## Express and Koa Support
Expand Down
14 changes: 7 additions & 7 deletions guides/misc/apollo.md
Expand Up @@ -18,7 +18,7 @@ npm install apollo-server-micro graphql
Once done, all you need to do is create a `graphql.js` file under the routes folder. Inside this, add the following starter code:

```js
const light = require('light');
const { light, Route } = require('light');
const { ApolloServer, gql } = require('apollo-server-micro');

const typeDefs = gql`
Expand All @@ -38,12 +38,12 @@ const resolvers = {
const apolloServer = new ApolloServer({ typeDefs, resolvers });
const graphqlHandler = apolloServer.createHandler();

module.exports = light({
path: '/graphql',
method: ['GET', 'POST'],
handler: graphqlHandler,
});

class graphql extends Route {
async handler() {
return graphqlHandler(this.req, this.res);
}
}
module.exports = light(graphql);
```

Most of the code that is provided is the starter code for Apollo. The only light related code is the `module.exports` at the bottom which simply tells light to run the following graphql handler when the route is `/graphql` with either GET (for the graphical interface) or POST (for the actual queries). *As always, if you are hosting on a serverless platform, you will need to point the route `/graphql` to this file.*
6 changes: 4 additions & 2 deletions guides/params.md
@@ -1,13 +1,15 @@
---
title: Params
title: params
subtitle: use the params function to fetch information from the url
---

## Introduction

The params function is a helper function to help extract parameters from URLs. While most frameworks such as express extract this on your behalf, it needs to be done explicitly since each environment has different way of getting the URL and the normalization step needs to happen first. Additionally, most of the time you do not need to have this step done so it is better to only have it done when needed. Finally, light's principle is to not assume anything and so this step needs to be explicit.

**NOTE: some serverless providers (such as Netlify) do not support this feature.**
**NOTE: some serverless providers (such as Netlify) do not support this feature as one file means one route.**

## THIS DOC IS INCOMPLETE. IT WILL BE UPDATED WHEN ROUTING IS UPDATED

## Setup

Expand Down
18 changes: 11 additions & 7 deletions guides/plugins.md
Expand Up @@ -28,15 +28,19 @@ As you can see, unlike middleware, with plugins we can run code both before and
Finally, we simply list the logger as plugin in the route.

```js
const light = require('light');
const { light, Route } = require('light');

module.exports = light({
path: '/',
plugins: [ logger ],
async handler(req, res) {
class Index extends Route {
get plugins() {
return [ logger ]; // you can have multiple plugins
}

async handler() {
return {
hello: 'world',
};
},
});
}
}

module.exports = light(Index);
```
18 changes: 9 additions & 9 deletions guides/query.md
Expand Up @@ -14,20 +14,20 @@ If there are multiple query parameters with the same name, it will return an arr
Simply import the `query` function and pass it the url of the request.

```javascript
const { light, query } = require('light');
const { light, Route, query } = require('light');

module.exports = light({
path: '/',

async handler(req) {
const { id, name } = await query(req.url);
class Index extends Route {
async handler() {
const { id, name } = await query(this.req.url);

return {
id,
name,
};
},
});
}
}

module.exports = light(Index);
```

After starting the dev server, you can make a request to [localhost:3000/?id=123&name=light](http://localhost:3000/?id=123&name=light) and expect a response of
Expand All @@ -39,4 +39,4 @@ After starting the dev server, you can make a request to [localhost:3000/?id=123
}
```

Note that by default all query parameters are strings, and you will need to convert them as necessary.
Note that by default all query parameters are strings, and you will need to cast them as necessary.
50 changes: 50 additions & 0 deletions guides/routes.md
@@ -0,0 +1,50 @@
---
title: routes
subtitle: the main entry point for your endpoints
---

## Introduction

Every light route must export a class with a `handler` function (which can be an async function) which is responsible for handling request. The handler will receive have access to `this.req` (IncomingMessage) and `this.res` (ServerResponse) (these may vary between different environments).

## Req/Res

The `this.req` and `this.res` variables are standard IncomingMessage and ServerResponse objects. In some environments, properties may be added or missing. For example, in AWS/Netlify mode, the `this.req` object will be missing some request and response properties because they were casted from event and context. You should only use properties that you know are going to be available in production.

## Return

If you choose to `return` from the function (instead of `send`ing), you must return a valid response. Whatever value that is returned will be serialized and sent as a response. You can choose to return JSON, String, or any other type that [micro](https://github.com/zeit/micro) supports under the hood.

```js
const { light, Route } = require('light');

class Index extends Route {
async handler() {
// this.req and this.res variables are available here

return {
hello: 'world',
};
// or
return 'hello world';
}
}

module.exports = light(Index);
```

## Send

Additionally you may use `micro`'s send function to return different kinds of responses. The send function can be imported from light and used anywhere in the handler. See [micro's documentation](https://github.com/zeit/micro#sendres-statuscode-data--null) for more details.

```js
const { light, Route, send } = require('light');

class Index extends Route {
async handler() {
send(this.res, 200, { hello: 'world' });
}
}

module.exports = light(Index);
```

0 comments on commit 7feaa30

Please sign in to comment.