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

Commit

Permalink
Write readme.md & readme.ru.md
Browse files Browse the repository at this point in the history
  • Loading branch information
Anton Konev committed Jun 16, 2015
1 parent 9d4fd11 commit 82170af
Show file tree
Hide file tree
Showing 2 changed files with 237 additions and 3 deletions.
117 changes: 114 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,114 @@
====
Тестовый проект по продаже лучших товаров сети
====
# Bemongo-stub

## Why?

When I began to study [methodology BEM](https://EN.bem.info/) and its tools it was difficult to find any example of making the real project.

To solve this problem, I wrote a small project that shows how to bring the data source (in this case [mongodb](http://www.mongodb.org/)) to the BEM-stack.

## What is Bemongo-stub?

It's a template repository to create your own [BEM](https://EN.bem.info/)-project with [mongodb](http://www.mongodb.org/).
It includes the examples to obtain & store data in [mongodb](http://www.mongodb.org/), also I made user authorization using [OAuth 2.0 API Yandex](https://oauth.yandex.EN/).

Used BEM-libraries for a project:

* [bem-bl](https://github.com/bem/bem-bl)
* [bem-components](https://github.com/bem/bem-components)

## Features of the implementation

* [Express](http://expressjs.com/) -- used for the routing of the project;
* [MongoDB](http://www.mongodb.org/) -- data storage (here we'll take :) ). I used mongodb in conjunction with the promises [bluebird](https://github.com/petkaantonov/bluebird);
* [ENB](http://enb-make.info/) -- tool that make builds of the bundles;
* [Passport Yandex](https://github.com/gurugray/passport yandex) -- authentication in the project through the [OAuth 2.0 API Yandex](https://oauth.yandex.com/).

Essentially the project is divided into 2 parts:
* `server` -- the server part;
* `static` -- the blocks and the bundles of the pages.
For implementation of the blocks I used `priv.js`, because the data will be taken dynamically.

## Installation requirements

* [Node.js 0.10+](http://nodejs.org) is a software platform based on JavaScript that allows you to create fast, scalable network applications;
* [Git Bash](http://msysgit.github.io/) – for users of the Windows operating system.

## Set

Clone the repository and install all the required dependencies:

```
git clone [email protected]:evilj0e/bemongo-stub.git my-bem-project
cd my-bem-project
npm run init # do Not use root (`root`) when you install npm and bower dependencies.
```

bower dependencies are installed when you run `npm run init` folder to `/static/vendors`.

For using the OAuth 2.0 API from Yandex you need to get the Client ID & Client secret keys for your own app. You can made that [here](https://oauth.yandex.com/).
After that you need change the config file for passport `server/lib/passport.js`:
```
passport.use(new PassportYandex({
clientID: '--- Client ID ---',
clientSecret: '--- Client secret ---',
callbackURL: 'http://localhost:3000/login/callback'
},
function(accessToken, refreshToken, profile, done) {
process.nextTick(function () {
db.upsertUser(profile.id, profile, done);
});
}
));
```

## Build and run the project

Build project using [ENB](https://bem.info/tools/bem/enb-bem-techs/).
Calling all teams `enb` possible hand from the folder `node_modules/.bin/enb` or you can use prepared by me shortcuts.

### Available shortcuts

```init``` -- initialization of the project and install all dependencies.

```jscs``` -- check codestyle with [jscs](http://jscs.info/);

```jshint``` -- check codestyle with [jshint](http://jshint.com/);

```csslint``` -- check codestyle with [csslint](http://csslint.net/);

```codestyle``` -- executes checks with jscs, jshint, csslint. Used as ```pre-commit hook```;

```test``` -- while doing nothing, because I don't wrote tests yet (lol);

```server``` -- build project and run a development server.;

```serverOnly``` -- just run a development server.

After running a development server project will be available at the address `http://localhost:3000`.
Press the key combination `Ctrl` + `C` or `` + `C` (for MAC) in the active terminal window to stop the server.

Shortcuts are invoked in the project folder as follows:
```bash
npm run %command_name%
```
`%command_name%` -- the name of the shortcut

## TODO
* Overwrite `controllers/db`;
* Remake redirects on authorization from / to requested url & don't use forced authorization on some pages;
* Write tests;
* Make CI integration;
* Make the logging;
* Add the [Helmet](https://github.com/helmetjs/helmet);
* Add the [Recluster](https://github.com/doxout/recluster);
* Add an example of the block templating on the client.

## Useful links

* [Create your own BEM project](https://EN.bem.info/articles/start-with-project-stub/)
* [Collect static page on BEM](https://EN.bem.info/tutorials/quick-start-static/)
* [Reference BEMJSON](https://EN.bem.info/technology/bemjson/current/commands/)
* [Step by step guide to i-bem.js](https://EN.bem.info/tutorials/bem-js-tutorial/)

## Useful tools
* [borschik](https://EN.bem.info/tools/optimizers/borschik/) — a simple but powerful Builder for text-based file formats
123 changes: 123 additions & 0 deletions README.ru.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
# Bemongo-stub

## Зачем?

Когда я начал изучать [методологию БЭМ](https://ru.bem.info/) и инструменты для создания проектов на ней, мне показалось, что это не только как писать, но и какая-то неповоротливая и неделимая комбинация инструментов, которая чисто 'про фронтенд'.
Первое впечатление было: "Это всё, конечно, классно, но как это можно использовать в жизни?"

Никаких примеров по тому как подружить full stack [БЭМ](https://ru.bem.info/) c чем-то, к сожалению, на момент моего знакомства небыло.
Особенно непросто разобраться с этой проблемой тем, кто только-только знакомится с технологиями БЭМ.

Именно для решения этой проблемы, я написал небольшой проект, который показывает как можно подружить источник данных (в данном случае [mongodb](http://www.mongodb.org/)) и стек технологий БЭМ.

## Что такое Bemongo-stub?

Шаблонный репозиторий для создания своего собственного [БЭМ](https://ru.bem.info/)-проекта в связке с [mongodb](http://www.mongodb.org/).
Содержит самый необходимый, на мой взгляд, функционал, включает пример простейшего скелета приложения
с получением, сохранением данных в [mongodb](http://www.mongodb.org/) и авторизацией пользователей через [OAuth 2.0 API Яндекса](https://oauth.yandex.ru/).

Проект реализован по БЭМ-методологии на `priv.js`, собирается [ENB](https://bem.info/tools/bem/enb-bem-techs/)-сборщиком.
В Bemongo-stub по умолчанию подключены основные БЭМ-библиотеки:

* [bem-bl](https://github.com/bem/bem-bl)
* [bem-components](https://github.com/bem/bem-components)

## Особенности реализации

Здесь я постарался всё написать довольно просто с несколькими роутами, которые показывают принципы работы по получению данных из базы, сохранению в неё, авторизации пользователя, сессией и всем остальным.

Используются:

* [Express](http://expressjs.com/) -- используется для нормального роутинга проекта;
* [MongoDB](http://www.mongodb.org/) -- хранение данных ресурса (отсюда мы будем всё брать :) ). Использую mongodb в связке с промисами [bluebird](https://github.com/petkaantonov/bluebird);
* [ENB](http://enb-make.info/) -- сборщик проекта;
* [Passport Yandex](https://github.com/gurugray/passport-yandex) -- аутентификация в проекте через [OAuth 2.0 API от Яндекс](https://oauth.yandex.ru/).

По своей сути проект разделён на 2 части:
* `server` -- вся серверная часть;
* `static` -- блоки и бандлы страниц.
Так как, данные будут у нас браться динамически, то для реализации блоков используется priv.js

## Требования к установке

* [Node.js 0.10+](http://nodejs.org) – это программная платформа, основанная на языке JavaScript и позволяющая легко создавать быстрые и масштабируемые сетевые приложения. Или [io.js](https://iojs.org/en/index.html), как альтернатива Node.js.
* [Git Bash](http://msysgit.github.io/) – для пользователей операционной системы Windows.

## Установка

Клонируем репозиторий и устанавливаем все необходимые зависимости:

```
git clone [email protected]:evilj0e/bemongo-stub.git my-bem-project
cd my-bem-project
npm run init # Не используйте права суперпользователя (`root`) при установке npm- и bower-зависимостей.
```

bower-зависимости устанавливаются при выполнении `npm run init` в папку `/static/vendors`.

Для работы с OAuth 2.0 API от Яндекс нужно получить токены для вашего экземпляра приложения [здесь](https://oauth.yandex.ru/).
И вставить эти данные в `server/lib/passport.js` в строки:
```
passport.use(new PassportYandex({
clientID: '--- Client ID ---',
clientSecret: '--- Client secret ---',
callbackURL: 'http://localhost:3000/login/callback'
},
function(accessToken, refreshToken, profile, done) {
process.nextTick(function () {
db.upsertUser(profile.id, profile, done);
});
}
));
```

## Сборка и запуск проекта

Собрать проект можно с помощью [ENB](https://bem.info/tools/bem/enb-bem-techs/).
Вызов всех команд `enb` возможен собственноручно из папки `node_modules/.bin/enb` или можно использовать подготовленные мной шорткаты.

### Доступные шорткаты

```init``` -- инициализация проекта и установка всех необходимых зависимостей;

```jscs``` -- проверяем кодстайл через [jscs](http://jscs.info/);

```jshint``` -- проверяем кодстайл через [jshint](http://jshint.com/);

```csslint``` -- проверяем кодстайл через [csslint](http://csslint.net/);

```codestyle``` -- выполяет проверки jscs, jshint, csslint. Используется в качестве ```pre-commit hook```;

```test``` -- пока ничего не делает, потому что нет тестов, но в ближайшем времени они будут;

```server``` -- сборка проекта и запуск разработческого сервера. Проект будет доступен по адресу `http://localhost:3000`;

```serverOnly``` -- просто запуск разработческого сервера.

После запуска разработческого сервера проект будет доступен по адресу `http://localhost:3000`.
Комбинация клавиш `Ctrl` + `C` или `` + `C` (для MAC) в активном окне терминала остановит сервер.

Шорткаты вызываются в директории проекта следующим образом:
```bash
npm run %command_name%
```
`%command_name%` -- название шортката

## TODO
* Переписать `controllers/db`;
* Написать тесты;
* Интегрировать с CI;
* Сделать нормально логгирование;
* Добавить [Helmet](https://github.com/helmetjs/helmet);
* Добавить [Recluster](https://github.com/doxout/recluster);
* Добавить пример шаблонизации на клиенте.

## Полезные ссылки

* [Создаем свой проект на БЭМ](https://ru.bem.info/articles/start-with-project-stub/)
* [Собираем статическую страницу на БЭМ](https://ru.bem.info/tutorials/quick-start-static/)
* [Справочное руководство по BEMJSON](https://ru.bem.info/technology/bemjson/current/bemjson/)
* [Пошаговое руководство по i-bem.js](https://ru.bem.info/tutorials/bem-js-tutorial/)

## Полезные инструменты
* [borschik](https://ru.bem.info/tools/optimizers/borschik/) — простой, но мощный сборщик файлов текстовых форматов

0 comments on commit 82170af

Please sign in to comment.