Skip to content
This repository has been archived by the owner on Oct 26, 2019. It is now read-only.

Commit

Permalink
Rename http-api
Browse files Browse the repository at this point in the history
  • Loading branch information
goto-bus-stop committed Feb 6, 2018
1 parent 46f59af commit d28145e
Show file tree
Hide file tree
Showing 13 changed files with 62 additions and 55 deletions.
33 changes: 17 additions & 16 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
# u-wave-api-v1
# u-wave-http-api

HTTP API plugin for üWave, the collaborative listening platform.

[Getting Started](#getting-started) - [API](#api) - [Building](#contributing) -
[License](#license)

> Note: üWave is still under development. Particularly the `u-wave-core` and
> `u-wave-api-v1` modules will change a lot before the "official" 1.0.0 release.
> Make sure to always upgrade both of them at the same time.
> `u-wave-http-api` modules will change a lot before the "official" 1.0.0
> release. Make sure to always upgrade both of them at the same time.
## Getting Started

```
npm install u-wave-api-v1
npm install u-wave-http-api
```

The module exports a middleware that can be used with express-style HTTP request
Expand All @@ -25,7 +25,7 @@ handlers.
Creates a middleware for use with [Express][] or another such library. The first
parameter is a `u-wave-core` instance. Available options are:

- `server` - An HTTP server instance. `u-wave-api-v1` uses WebSockets, and it
- `server` - An HTTP server instance. `u-wave-http-api` uses WebSockets, and it
needs an HTTP server to listen to for incoming WebSocket connections. An
example for how to obtain this server from an Express app is shown below.
- `socketPort` - The WebSocket server can also listen on its own port instead
Expand All @@ -37,16 +37,16 @@ parameter is a `u-wave-core` instance. Available options are:
pass an object with ReCaptcha options. The only available option is `secret`,
which is the ReCaptcha secret obtained from the "Server-side integration"
panel on your [ReCaptcha site admin page][recaptcha].
- `mailTransport` - [nodemailer](https://nodemailer.com) SMTP options or a transport object,
used to send password reset emails.
- `mailTransport` - [nodemailer](https://nodemailer.com) SMTP options or a
transport object, used to send password reset emails.
- `onError` - Error handler function, use for recording errors. First parameter
is the request object that caused the error, second is the error itself.

```js
import express from 'express';
import stubTransport from 'nodemailer-stub-transport';
import uwave from 'u-wave-core';
import createHttpApi from 'u-wave-api-v1';
import createHttpApi from 'u-wave-http-api';

const app = express();
const server = app.listen();
Expand All @@ -69,14 +69,14 @@ app.use('/v1', api);

### api.attachUwaveToRequest()

Returns a middleware that attaches the üWave core object and the üWave api-v1
Returns a middleware that attaches the üWave core object and the üWave http-api
object to the request. The `u-wave-core` instance will be available as
`req.uwave`, and the `u-wave-api-v1` instance will be available as
`req.uwaveApiV1`. This is useful if you want to access these objects in custom
routes, that are not in the `u-wave-api-v1` namespace. E.g.:
`req.uwave`, and the `u-wave-http-api` instance will be available as
`req.uwaveHttp`. This is useful if you want to access these objects in custom
routes, that are not in the `u-wave-http-api` namespace. E.g.:

```js
app.use('/v1', api);
app.use('/api', api);

// A custom profile page.
app.get('/profile/:user', api.attachUwaveToRequest(), (req, res) => {
Expand All @@ -89,7 +89,8 @@ app.get('/profile/:user', api.attachUwaveToRequest(), (req, res) => {

## Contributing

There is a development server included in this repository. To use it, first you have to clone and install u-wave-core.
There is a development server included in this repository. To use it, first you
have to clone and install u-wave-core.

```bash
git clone https://github.com/u-wave/core u-wave-core
Expand All @@ -101,8 +102,8 @@ npm link
Then you can clone and install the HTTP API:

```bash
git clone https://github.com/u-wave/api-v1 u-wave-api-v1
cd u-wave-api-v1
git clone https://github.com/u-wave/http-api u-wave-http-api
cd u-wave-http-api
npm install
# Add our local u-wave-core
npm link u-wave-core
Expand Down
2 changes: 1 addition & 1 deletion dev/u-wave-api-dev-server
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ function start() {
console.log(`Now listening on ${port}`);
});

const apiUrl = '/v1';
const apiUrl = '/api';

app.use(apiUrl, createWebApi(uw, {
recaptcha: { secret: recaptchaTestKeys.secret },
Expand Down
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
{
"name": "u-wave-api-v1",
"name": "u-wave-http-api",
"version": "0.3.0",
"description": "HTTP API interface for üWave.",
"license": "MIT",
"repository": "u-wave/api-v1",
"repository": "u-wave/http-api",
"author": "Sooyou <[email protected]>",
"contributors": [
"Felix Wong <[email protected]>",
"Goz3rr <[email protected]>",
"Renée Kooi <[email protected]>",
"xBytez <[email protected]>"
],
"main": "dist/u-wave-api-v1.js",
"module": "dist/u-wave-api-v1.es.js",
"main": "dist/u-wave-http-api.js",
"module": "dist/u-wave-http-api.es.js",
"engines": {
"node": ">= 8.9"
},
Expand Down
16 changes: 8 additions & 8 deletions src/ApiV1.js → src/HttpApi.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,21 +34,21 @@ options are used to attach the WebSocket server to the correct HTTP server.
An example of how to attach the WebSocket server to an existing HTTP server
using Express:
import webApi from 'u-wave-api-v1';
import httpApi from 'u-wave-http-api';
const app = express();
const server = app.listen(80);
app.use('/v1', webApi(uwave, {
app.use('/api', httpApi(uwave, {
server: server,
...
}));
Alternatively, you can provide a port for the socket server to listen on:
import webApi from 'u-wave-api-v1';
import httpApi from 'u-wave-http-api';
const app = express();
app.use('/v1', webApi(uwave, {
app.use('/api', httpApi(uwave, {
socketPort: 6042,
...
}));
Expand All @@ -74,7 +74,7 @@ function defaultCreatePasswordResetEmail({ token, requestUrl }) {
};
}

export default class ApiV1 extends Router {
export default class UwaveHttpApi extends Router {
constructor(uw, options = {}) {
if (!uw || !('mongo' in uw)) {
throw new TypeError('Expected a u-wave-core instance in the first parameter. If you are ' +
Expand Down Expand Up @@ -122,7 +122,7 @@ export default class ApiV1 extends Router {
.use(addFullUrl())
.use(this.attachUwaveToRequest())
.use(this.passport.authenticate('jwt'))
.use(rateLimit('api-v1-http', { max: 500, duration: 60 * 1000 }));
.use(rateLimit('api-http', { max: 500, duration: 60 * 1000 }));

this
.use('/auth', authenticate(this, {
Expand All @@ -149,10 +149,10 @@ export default class ApiV1 extends Router {
}

/**
* Create middleware to attach the u-wave-core instance and the u-wave-api-v1
* Create middleware to attach the u-wave-core instance and the u-wave-http-api
* instance to incoming requests. This can be used to access eg. configuration
* options or session information inside other routes (ones not added by
* u-wave-api-v1).
* u-wave-http-api).
*
* @return {Function} Middleware.
*/
Expand Down
14 changes: 7 additions & 7 deletions src/controllers/authenticate.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ import beautifyDuplicateKeyError from '../utils/beautifyDuplicateKeyError';
import toItemResponse from '../utils/toItemResponse';
import toListResponse from '../utils/toListResponse';

const log = createDebug('uwave:api:v1:auth');
const log = createDebug('uwave:http:auth');

function seconds(str) {
return Math.floor(ms(str) / 1000);
Expand All @@ -30,22 +30,22 @@ export function getCurrentUser(req) {
}

export function getAuthStrategies(req) {
const { passport } = req.uwaveApiV1;
const { passport } = req.uwaveHttp;

return toListResponse(
passport.strategies(),
{ url: req.fullUrl },
);
}

export async function refreshSession(res, v1, user, options) {
export async function refreshSession(res, api, user, options) {
const token = await jwt.sign(
{ id: user.id },
options.secret,
{ expiresIn: '31d' },
);

const socketToken = await v1.sockets.createAuthToken(user);
const socketToken = await api.sockets.createAuthToken(user);

if (options.session === 'cookie') {
const serialized = cookie.serialize('uwsession', token, {
Expand All @@ -72,7 +72,7 @@ export async function login(options, req, res) {
throw new PermissionError('You have been banned.');
}

const { token, socketToken } = await refreshSession(res, req.uwaveApiV1, user, {
const { token, socketToken } = await refreshSession(res, req.uwaveHttp, user, {
...options,
session: sessionType,
});
Expand All @@ -92,7 +92,7 @@ export async function socialLoginCallback(options, req, res) {
throw new PermissionError('You have been banned.');
}

await refreshSession(res, req.uwaveApiV1, user, {
await refreshSession(res, req.uwaveHttp, user, {
...options,
session: 'cookie',
});
Expand All @@ -113,7 +113,7 @@ export async function socialLoginCallback(options, req, res) {
}

export async function getSocketToken(req) {
const { sockets } = req.uwaveApiV1;
const { sockets } = req.uwaveHttp;
const socketToken = await sockets.createAuthToken(req.user);
return toItemResponse({ socketToken }, {
url: req.fullUrl,
Expand Down
8 changes: 4 additions & 4 deletions src/controllers/now.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,12 @@ import { serializePlaylist } from '../utils/serialize';
// eslint-disable-next-line import/prefer-default-export
export async function getState(req) {
const uw = req.uwave;
const v1 = req.uwaveApiV1;
const api = req.uwaveHttp;
const { user } = req;

const User = uw.model('User');

const guests = v1.getGuestCount();
const guests = api.getGuestCount();
const motd = uw.getMotd();
const booth = getBoothData(uw);
const users = uw.redis.lrange('users', 0, -1)
Expand All @@ -20,8 +20,8 @@ export async function getState(req) {
const waitlistLocked = uw.redis.get('waitlist:lock').then(Boolean);
const activePlaylist = user ? user.getActivePlaylistID() : null;
const playlists = user ? user.getPlaylists() : null;
const socketToken = user ? v1.sockets.createAuthToken(user) : null;
const authStrategies = v1.passport.strategies();
const socketToken = user ? api.sockets.createAuthToken(user) : null;
const authStrategies = api.passport.strategies();
const time = Date.now();

const state = await Promise.props({
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/playlists.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import toItemResponse from '../utils/toItemResponse';
import toListResponse from '../utils/toListResponse';
import toPaginatedResponse from '../utils/toPaginatedResponse';

const debug = createDebug('uwave:api:v1:playlists');
const debug = createDebug('uwave:http:playlists');

export async function getPlaylists(req) {
const playlists = await req.user.getPlaylists();
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/search.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import createDebug from 'debug';
import { NotFoundError } from '../errors';
import toListResponse from '../utils/toListResponse';

const log = createDebug('uwave:api:v1:search');
const log = createDebug('uwave:http:search');

export function searchAll(req) {
const uw = req.uwave;
Expand Down
13 changes: 8 additions & 5 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import ApiV1 from './ApiV1';
import UwaveHttpApi from './HttpApi';

export default function createApiV1(uw, opts) {
return new ApiV1(uw, opts);
export default function createHttpApi(uw, opts) {
return new UwaveHttpApi(uw, opts);
}

createApiV1.V1 = ApiV1;
createApiV1.ApiV1 = ApiV1;
createHttpApi.HttpApi = UwaveHttpApi;

// Backwards compat?
createHttpApi.V1 = UwaveHttpApi;
createHttpApi.ApiV1 = UwaveHttpApi;
7 changes: 5 additions & 2 deletions src/middleware/attachUwaveMeta.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
export default function attachUwaveMeta(apiV1, uw) {
export default function attachUwaveMeta(httpApi, uw) {
return (req, res, next) => {
if (!req.uwave) {
req.uwaveApiV1 = apiV1;
req.uwaveHttp = httpApi;
req.uwave = uw;

// Backwards compat?
req.uwaveApiV1 = httpApi;
}
next();
};
Expand Down
2 changes: 1 addition & 1 deletion src/middleware/errorHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import {
CombinedError,
} from '../errors';

const debug = createDebug('uwave:api:v1:error');
const debug = createDebug('uwave:http:error');

function toErrorResponse(errors) {
return {
Expand Down
4 changes: 2 additions & 2 deletions src/routes/authenticate.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import protect from '../middleware/protect';
import checkFields from '../middleware/checkFields';
import * as controller from '../controllers/authenticate';

export default function authenticateRoutes(v1, options) {
const { passport } = v1;
export default function authenticateRoutes(api, options) {
const { passport } = api;

const auth = router()
// GET /auth/ - Show current user information.
Expand Down
6 changes: 3 additions & 3 deletions src/routes/chat.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,20 @@ import * as controller from '../controllers/chat';

export default function chatRoutes() {
return router()
// DELETE /v1/chat/ - Clear the chat (delete all messages).
// DELETE /chat/ - Clear the chat (delete all messages).
.delete(
'/',
protect(ROLE_MODERATOR),
route(controller.deleteAll),
)
// DELETE /v1/chat/user/:id - Delete all messages by a user.
// DELETE /chat/user/:id - Delete all messages by a user.
.delete(
'/user/:id',
protect(ROLE_MODERATOR),
checkFields(validations.deleteChatByUser),
route(controller.deleteByUser),
)
// DELETE /v1/chat/:id - Delete a chat message.
// DELETE /chat/:id - Delete a chat message.
.delete(
'/:id',
protect(ROLE_MODERATOR),
Expand Down

1 comment on commit d28145e

@fawaf
Copy link
Member

@fawaf fawaf commented on d28145e Feb 6, 2018

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

woot! we wanted this for so long.

Please sign in to comment.