Skip to content

Commit

Permalink
Typescript Template Review (#248)
Browse files Browse the repository at this point in the history
* Updated template with new config, structure and swc usage

* Update dependabot.yml

* Update nodejs.yml

* Briefly reviewed README.md

* Moved eslint config in .eslintrc file

* Aligned comments

* Reviewed pre-commit hook, Dockerfile and updated dependencies

* Update README.md

* Updated service dependencies

* Specified node version in Dockerfile

* Removed node-14 support from Github actions

* Updated lc39 type in test helper

* refactor(template-structure): major template review

Included changes aim to provide a simpler base template, retaining type checking but also reducing time to run tests. In addition Jest is swapped with Tap and swc is employed only for test transpiling, while tsc is still employed for building the source code.

BREAKING CHANGE:

* test: review coverage config

* build(runtime): add tini as image entrypoint

* build(dockerfile): fix CMD instruction to allow variables expansion

* chore(deps): update service dependencies

* Update package.json

Co-authored-by: Giorgio Acquati <[email protected]>

* refactor: remove comments from tsconfig

* refactor: remove useful files from .dockerignore

* chore(deps): update template dependencies

* build: update which files are copied in the final image stage

Co-authored-by: Giorgio Acquati <[email protected]>
  • Loading branch information
danibix95 and GioAc96 authored Oct 12, 2022
1 parent 2ac9d26 commit 26fd8f9
Show file tree
Hide file tree
Showing 27 changed files with 9,441 additions and 6,969 deletions.
9 changes: 8 additions & 1 deletion .dockerignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
.nyc_output
build/Release
coverage
dist
node_modules
__tests__
docs
tests
.dockerignore
*.env
*.log*
Expand All @@ -17,3 +18,9 @@ docs
.yarn-integrity
Dockerfile
README.md
tsconfig.tsbuildinfo
.husky
scripts
.github
.mia-template
.prettierrc
56 changes: 56 additions & 0 deletions .eslintrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
{
"extends": [
"@mia-platform/eslint-config-mia"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"sourceType": "module"
},
"ignorePatterns": [
"*.d.ts"
],
"rules": {
"sort-imports": [
"error",
{
"ignoreCase": true,
"ignoreDeclarationSort": true,
"ignoreMemberSort": true,
"allowSeparatedGroups": true
}
],
"no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": "error",
"no-shadow": "off",
"@typescript-eslint/no-shadow": [
"error"
]
},
"overrides": [
{
"files": [
"*.test.ts",
"tests/helpers/*"
],
"rules": {
"no-await-in-loop": "off",
"default-case": "off",
"guard-for-in": "off",
"no-shadow": "off",
"id-length": "off",
"max-depth": "off",
"max-lines": "off",
"max-nested-callbacks": "off",
"max-statements": "off",
"@typescript-eslint/no-shadow": "off",
"no-loop-func": "off"
}
}
],
"globals": {
"NodeJS": true
},
"plugins": [
"@typescript-eslint"
]
}
19 changes: 1 addition & 18 deletions .github/dependabot.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,22 +3,5 @@ updates:
- package-ecosystem: npm
directory: "/"
schedule:
interval: daily
time: "04:00"
interval: weekly
open-pull-requests-limit: 10
ignore:
- dependency-name: fastify
versions:
- 3.11.0
- 3.12.0
- 3.13.0
- 3.14.0
- 3.14.1
- 3.14.2
- dependency-name: typescript
versions:
- 4.1.3
- 4.1.4
- 4.1.5
- 4.2.2
- 4.2.3
4 changes: 2 additions & 2 deletions .github/workflows/nodejs.yml
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ jobs:

strategy:
matrix:
node-version: [12.x, 14.x]
node-version: [16.x, 18.x]

steps:
- uses: actions/checkout@v2
- uses: actions/checkout@v3
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
Expand Down
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,5 @@ node_modules
.yarn-integrity
!default.env
.npmrc
dist
dist
tsconfig.tsbuildinfo
4 changes: 2 additions & 2 deletions .mia-template/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,9 @@ npm run build
This command will create the project `.js` sources inside the `dist/` folder.
## Local Development
To develop the service locally you need:
- Node 10+
- Node 16+

To setup node, please if possible try to use [nvm][nvm], so you can manage multiple
To set up node, please if possible try to use [nvm][nvm], so you can manage multiple
versions easily. Once you have installed nvm, you can go inside the directory of the project and simply run
`nvm install`, the `.nvmrc` file will install and select the correct version if you don’t already have it.

Expand Down
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
lts/fermium
lts/gallium
5 changes: 5 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"semi": false,
"singleQuote": true,
"arrowParens": "avoid"
}
28 changes: 23 additions & 5 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,24 +1,31 @@
FROM node:14.18.0-alpine as build
FROM node:16.17.1-alpine as build

ARG COMMIT_SHA=<not-specified>
ENV NODE_ENV=production
ENV NPM_CONFIG_CACHE="/tmp"

WORKDIR /build-dir

COPY package.json .
COPY package-lock.json .

# install also DEV dependencies to enable Typescript compilation
RUN npm ci

COPY . .

# compile Typescript to Javascript
RUN npm run build

RUN echo "mia_template_service_name_placeholder: $COMMIT_SHA" >> ./commit.sha

########################################################################################################################

FROM node:14.18.0-alpine
FROM node:16.17.1-alpine

# Resources
# - https://github.com/krallin/tini
# - https://cloud.google.com/architecture/best-practices-for-building-containers#signal-handling
RUN apk add --no-cache tini

LABEL maintainer="%CUSTOM_PLUGIN_CREATOR_USERNAME%" \
name="mia_template_service_name_placeholder" \
Expand All @@ -30,11 +37,22 @@ ENV NODE_ENV=production
ENV LOG_LEVEL=info
ENV SERVICE_PREFIX=/
ENV HTTP_PORT=3000
ENV NPM_CONFIG_CACHE="/tmp"

WORKDIR /home/node/app

COPY --from=build /build-dir ./
# copy only needed files
COPY --from=build /build-dir/package.json package.json
COPY --from=build /build-dir/package-lock.json package-lock.json
COPY --from=build /build-dir/LICENSE LICENSE
COPY --from=build /build-dir/CHANGELOG.md CHANGELOG.md
COPY --from=build /build-dir/dist dist

# install only dependencies required to run the service
RUN npm ci --omit=dev

USER node

CMD ["npm", "-s", "start", "--", "--port", "${HTTP_PORT}", "--log-level", "${LOG_LEVEL}", "--prefix=${SERVICE_PREFIX}"]
ENTRYPOINT ["/sbin/tini", "--"]

CMD ./node_modules/.bin/lc39 ./dist/index.js --port=${HTTP_PORT} --log-level=${LOG_LEVEL}
63 changes: 46 additions & 17 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,17 @@ A more detailed description on how to create and save a Microservice can be foun

## Look inside your repository

After having created your first microservice (based on this template) you will be able to access to its git repository from the DevOps Console. Inside this repository you will find an [index.ts](https://github.com/mia-platform-marketplace/Typescript-LC39-Template/blob/master/index.ts) file with the following lines of code:
After having created your first microservice (based on this template) you will be able to access to its git repository from the DevOps Console. Inside this repository you will find an [index.ts](./src/index.ts) file with the following lines of code:

```js
/* eslint require-await: 0 */
'use strict'
```typescript
import { envSchema } from './env'
import { getMetrics } from './metrics'
import { UndecoratedService } from './types'

const customService = require('@mia-platform/custom-plugin-lib')()
/* eslint-disable-next-line no-unused-vars */
module.exports = customService(async function index(service) {
const customService = require('@mia-platform/custom-plugin-lib')(envSchema)

// eslint-disable-next-line @typescript-eslint/no-unused-vars
module.exports = customService(async(service: UndecoratedService) => {

/*
* Insert your code here.
Expand All @@ -58,7 +60,7 @@ As you may have noticed in the snippet of code in the previous section, you will
`custom-plugin-lib` is a [node.js](https://github.com/mia-platform/custom-plugin-lib) library developed by Mia-Platform. This library contains configurations and functions that will help you to modify your template with easiness.
In particular, you will use the following function for our library

```javascript
```typescript
service.addRawCustomPlugin(httpVerb, path, handler, schema)
```

Expand All @@ -72,13 +74,14 @@ and you will pass to it the following parameters:
A more detailed description on how to use our `custom-plugin-lib` to define the behavior of your microservice in response to an HTTP request can be found in [Create a Node Custom Microservices](https://docs.mia-platform.eu/development_suite/api-console/api-design/plugin_baas_4/) section of Mia-Platform documentation.

In order to proceed, you need to define a handler, a schema and pass them as parameters to this function.
Below, you can see how the *index.tss* file will look like after having defined all the parameters required by `service.addRawCustomPlugin` function:
Below, you can see how the *index.ts* file will look like after having defined all the parameters required by `service.addRawCustomPlugin` function:

```js
/* eslint require-await: 0 */
'use strict'
```typescript
import { envSchema } from './env'
import { getMetrics } from './metrics'
import { UndecoratedService } from './types'

const customService = require('@mia-platform/custom-plugin-lib')()
const customService = require('@mia-platform/custom-plugin-lib')(envSchema)

// response scheme
const helloSchema = {
Expand All @@ -95,10 +98,15 @@ const helloSchema = {

interface HelloRequest { }

module.exports = customService(async function index(service: DecoratedFastify) {
service.addRawCustomPlugin('GET', '/hello', async function (request:DecoratedRequest<HelloRequest>, reply:FastifyReply<any>) {
return { message: 'Hello World' }
}, schema)
module.exports = customService(async(service: UndecoratedService) => {
service.addRawCustomPlugin(
'GET',
'/hello',
async function (request:DecoratedRequest<HelloRequest>, reply:FastifyReply<any>) {
return { message: 'Hello World' }
},
schema
)
})
```

Expand Down Expand Up @@ -143,6 +151,27 @@ you should see the following message:

Congratulations! You have successfully learnt how to modify a blank template into an _Hello World_ TypeScript microservice!

## Developer Tips

### NPM Build Commands

This project adopts [SWC](https://swc.rs/) to compile Typescript into Javascript. One downside of using SWC is that types are not checked anymore.
Since types are the main reason of introducing Typescript, losing such feature would invalidate its proposition.

For this reason, it has been decided to combine `tsc` type checking with `swc` compiling power. This is reflected in the `npm build` script defined in the `package.json` file. Indeed, that script at first launches a types verification procedure and then, in case of success, it transpiles Typescript into Javascript.

### NPM Test

In this repository are offered two options to ensure that tests are passing before any source code is committed:

- _pre-commit hook_, which can be installed by executing the following npm script:

npm run install-precommit

- _execute tests in watch mode_, that is continuously running tests on parts of the source code that were edited. This can be achieved running this npm script:

npm run dev

[github-actions]: https://github.com/mia-platform-marketplace/Typescript-LC39-Template/actions
[github-actions-svg]: https://github.com/mia-platform-marketplace/Typescript-LC39-Template/workflows/Node.js%20CI/badge.svg
[coverall-svg]: https://coveralls.io/repos/github/mia-platform-marketplace/Typescript-LC39-Template/badge.svg?branch=master
Expand Down
58 changes: 0 additions & 58 deletions __tests__/index.test.ts

This file was deleted.

18 changes: 18 additions & 0 deletions build.tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"declaration": true,
"declarationMap": true,
"sourceMap": true,
"inlineSourceMap": false,
"outDir": "./dist"
},
"include": [
"src/**/*"
],
"exclude": [
"node_modules",
"tests",
"dist"
]
}
2 changes: 1 addition & 1 deletion default.env
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
LOG_LEVEL=trace
LOG_LEVEL=debug
USERID_HEADER_KEY=userid
GROUPS_HEADER_KEY=usergroups
CLIENTTYPE_HEADER_KEY=clienttype
Expand Down
1 change: 0 additions & 1 deletion index.d.ts

This file was deleted.

Loading

0 comments on commit 26fd8f9

Please sign in to comment.