@volcanicminds/backend 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/.dockerignore ADDED
@@ -0,0 +1,2 @@
1
+ node-modules
2
+ **/node_modules
package/.nvmrc ADDED
@@ -0,0 +1 @@
1
+ v16.13.2
@@ -0,0 +1,5 @@
1
+ node_modules
2
+
3
+ # Ignore artifacts:
4
+ build
5
+ coverage
package/.prettierrc ADDED
@@ -0,0 +1,9 @@
1
+ {
2
+ "semi": false,
3
+ "singleQuote": true,
4
+ "useTabs": false,
5
+ "bracketSpacing": true,
6
+ "trailingComma": "none",
7
+ "tabWidth": 2,
8
+ "printWidth": 120
9
+ }
package/DOCKER.md ADDED
@@ -0,0 +1,23 @@
1
+ # Docker
2
+
3
+ try to use these to run the app in a docker node:16-alpine image:
4
+
5
+ ```js
6
+
7
+ // easy
8
+ docker build -t volcanic-backend .
9
+ docker run -dp 2230:2230 -it volcanic-backend
10
+
11
+ // detached mode with autoremove when stopped
12
+ docker run --rm -dp 2230:2230 -it volcanic-backend
13
+
14
+ // attached mode with autoremove when stopped
15
+ docker run --rm -p 2230:2230 -it volcanic-backend
16
+
17
+ // remove
18
+ docker image rm volcanic-backend
19
+
20
+ // prune all
21
+ docker system prune --all
22
+
23
+ ```
package/Dockerfile ADDED
@@ -0,0 +1,21 @@
1
+ FROM node:16-alpine
2
+
3
+ LABEL version="0.1.0"
4
+ LABEL description="Volcanic Backend"
5
+ LABEL maintainer="Developers <developers@volcanicminds.com>"
6
+
7
+ # Create app directory
8
+ WORKDIR /usr/src/app
9
+
10
+ # Install app dependencies
11
+ COPY package*.json yarn.lock ./
12
+ COPY lib lib/
13
+
14
+ RUN yarn install
15
+ RUN apk --no-cache add curl
16
+
17
+ # Bundle app source
18
+ COPY . .
19
+
20
+ # EXPOSE 2230
21
+ CMD [ "yarn", "start" ]
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Volcanic Minds
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,146 @@
1
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
2
+ [![opensource](https://img.shields.io/badge/open-source-blue)](https://en.wikipedia.org/wiki/Open_source)
3
+ [![volcanic-backend](https://img.shields.io/badge/volcanic-minds-orange)](https://github.com/volcanicminds/volcanic-backend)
4
+
5
+ # volcanic-backend
6
+
7
+ ## Based on
8
+
9
+ Based on [Fastify](https://www.fastify.io) ([GitHub](https://github.com/fastify/fastify)).
10
+
11
+ Based on [Apollo Server](https://www.apollographql.com) ([GitHub](https://github.com/apollographql/apollo-server)).
12
+
13
+ And, what you see in [package.json](package.json).
14
+
15
+ ## Environment (example)
16
+
17
+ ```ruby
18
+ NODE_ENV=development
19
+
20
+ HOST=0.0.0.0
21
+ PORT=2230
22
+
23
+ # LOG_LEVEL: trace, debug, info, warn, error, fatal
24
+ LOG_LEVEL=info
25
+ LOG_COLORIZE=true
26
+ LOG_TIMESTAMP=true
27
+ LOG_TIMESTAMP_READABLE=true
28
+ LOG_FASTIFY=false
29
+
30
+ GRAPHQL=false
31
+ SWAGGER=true
32
+ SWAGGER_TITLE=API Documentation
33
+ SWAGGER_DESCRIPTION=List of available APIs and schemes to use
34
+ SWAGGER_VERSION=0.1.0
35
+
36
+ SRV_CORS=false
37
+ SRV_HELMET=false
38
+ SRV_RATELIMIT=false
39
+ SRV_COMPRESS=false
40
+ ```
41
+
42
+ For docker may be useful set HOST as 0.0.0.0 (instead 127.0.0.1).
43
+
44
+ ## How to upgrade packages
45
+
46
+ ```js
47
+ yarn upgrade-deps
48
+ ```
49
+
50
+ ## How to run
51
+
52
+ ```js
53
+ yarn dev
54
+ yarn start
55
+ yarn prod
56
+ ```
57
+
58
+ When you execute `yarn dev` the server is restarted whenever a .js/.ts file is changed (thanks to [nodemon](https://www.npmjs.com/package/nodemon))
59
+
60
+ ## How to test (logic)
61
+
62
+ ```js
63
+ yarn test
64
+ yarn test -t 'Logging'
65
+ ```
66
+
67
+ Refer to jest for more options.
68
+
69
+ ## Logging levels
70
+
71
+ In the .env file you can change log settings in this way:
72
+
73
+ ```ruby
74
+ # LOG_LEVEL: trace, debug, info, warn, error, fatal
75
+ LOG_LEVEL=debug
76
+ LOG_TIMESTAMP=true
77
+ LOG_TIMESTAMP_READABLE=false
78
+ LOG_COLORIZE=true
79
+ ```
80
+
81
+ Log levels:
82
+
83
+ - **trace**: useful and useless messages, verbose mode
84
+ - **debug**: well, for debugging purposes.. you know what I mean
85
+ - **info**: minimal logs necessary for understand that everything is working fine
86
+ - **warn**: useful warnings if the environment is controlled
87
+ - **error**: print out errors even if not blocking/fatal errors
88
+ - **fatal**: ok you are dead now, but you want to know why?
89
+
90
+ a bit of code:
91
+
92
+ ```js
93
+ log.trace('Annoying message')
94
+ log.debug('Where is my bug?')
95
+ log.info('Useful information')
96
+ log.warn(`Hey pay attention: ${message}`)
97
+ log.error(`Catch an exception: ${message}`)
98
+ log.fatal(`Catch an exception: ${message} even if it's too late, sorry.`)
99
+
100
+ // use the proper flag to check if the level log is active (to minimize phantom loads)
101
+ log.i && log.info('Total commissions -> %d', aHugeCalculation())
102
+
103
+ // f.e.
104
+ log.t && log.trace('print a message')
105
+ log.d && log.debug('print a message')
106
+ log.i && log.info('print a message')
107
+ log.w && log.warn('print a message')
108
+ log.e && log.error('print a message')
109
+ log.f && log.fatal('print a message')
110
+ ```
111
+
112
+ Other settings:
113
+
114
+ - **LOG_TIMESTAMP** (bool): add timestamp in each line
115
+ - **LOG_TIMESTAMP_READABLE** (bool): if timestamp is enabled this specify a human-readable format (worst performance)
116
+ - **LOG_COLORIZE** (bool): add a bit of colors
117
+
118
+ Defaults, see [logger.ts](./lib/util/logger.ts):
119
+
120
+ ```js
121
+ const logColorize = yn(LOG_COLORIZE, true)
122
+ const logTimestamp = yn(LOG_TIMESTAMP, true)
123
+ const logTimestampReadable = yn(LOG_TIMESTAMP_READABLE, true)
124
+ ```
125
+
126
+ ## Swagger
127
+
128
+ In the .env file you can change swagger settings in this way:
129
+
130
+ ```ruby
131
+ SWAGGER=true
132
+ SWAGGER_TITLE=API Documentation
133
+ SWAGGER_DESCRIPTION=List of available APIs and schemes to use
134
+ SWAGGER_VERSION=0.1.0
135
+ ```
136
+
137
+ ## Fastify modules
138
+
139
+ In the .env file you can activate some modules in this way:
140
+
141
+ ```ruby
142
+ SRV_CORS=false
143
+ SRV_HELMET=false
144
+ SRV_RATELIMIT=false
145
+ SRV_COMPRESS=false
146
+ ```
package/TODO.md ADDED
@@ -0,0 +1,12 @@
1
+ # TODO
2
+
3
+ - roles
4
+ - database psql
5
+ - models
6
+ - validations
7
+ - authentication
8
+ - hooks (come middlewares esposti)
9
+ - testare middlewares
10
+ - usare progetto come modulo
11
+ - creare modulo npm
12
+ - metrics (plugin?)
package/jest.config.js ADDED
@@ -0,0 +1,188 @@
1
+ // For a detailed explanation regarding each configuration property, visit:
2
+ // https://jestjs.io/docs/en/configuration.html
3
+
4
+ module.exports = {
5
+ // All imported modules in your tests should be mocked automatically
6
+ // automock: false,
7
+
8
+ // Stop running tests after `n` failures
9
+ // bail: 0,
10
+
11
+ // The directory where Jest should store its cached dependency information
12
+ // cacheDirectory: "C:\\Users\\davide\\AppData\\Local\\Temp\\jest",
13
+
14
+ // Automatically clear mock calls and instances between every test
15
+ // clearMocks: false,
16
+
17
+ // Indicates whether the coverage information should be collected while executing the test
18
+ collectCoverage: true,
19
+
20
+ // An array of glob patterns indicating a set of files for which coverage information should be collected
21
+ // collectCoverageFrom: undefined,
22
+
23
+ // The directory where Jest should output its coverage files
24
+ // coverageDirectory: undefined,
25
+
26
+ // An array of regexp pattern strings used to skip coverage collection
27
+ // coveragePathIgnorePatterns: [
28
+ // "\\\\node_modules\\\\"
29
+ // ],
30
+
31
+ // Indicates which provider should be used to instrument code for coverage
32
+ coverageProvider: "v8",
33
+
34
+ // A list of reporter names that Jest uses when writing coverage reports
35
+ // coverageReporters: [
36
+ // "json",
37
+ // "text",
38
+ // "lcov",
39
+ // "clover"
40
+ // ],
41
+
42
+ // An object that configures minimum threshold enforcement for coverage results
43
+ // coverageThreshold: undefined,
44
+
45
+ // A path to a custom dependency extractor
46
+ // dependencyExtractor: undefined,
47
+
48
+ // Make calling deprecated APIs throw helpful error messages
49
+ // errorOnDeprecated: false,
50
+
51
+ // Force coverage collection from ignored files using an array of glob patterns
52
+ // forceCoverageMatch: [],
53
+
54
+ // A path to a module which exports an async function that is triggered once before all test suites
55
+ // globalSetup: undefined,
56
+
57
+ // A path to a module which exports an async function that is triggered once after all test suites
58
+ // globalTeardown: undefined,
59
+
60
+ // A set of global variables that need to be available in all test environments
61
+ // globals: {},
62
+
63
+ // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
64
+ // maxWorkers: "50%",
65
+
66
+ // An array of directory names to be searched recursively up from the requiring module's location
67
+ // moduleDirectories: [
68
+ // "node_modules"
69
+ // ],
70
+
71
+ // An array of file extensions your modules use
72
+ // moduleFileExtensions: [
73
+ // "js",
74
+ // "json",
75
+ // "jsx",
76
+ // "ts",
77
+ // "tsx",
78
+ // "node"
79
+ // ],
80
+
81
+ // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
82
+ // moduleNameMapper: {},
83
+
84
+ // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
85
+ // modulePathIgnorePatterns: [],
86
+
87
+ // Activates notifications for test results
88
+ // notify: false,
89
+
90
+ // An enum that specifies notification mode. Requires { notify: true }
91
+ // notifyMode: "failure-change",
92
+
93
+ // A preset that is used as a base for Jest's configuration
94
+ // preset: undefined,
95
+
96
+ // Run tests from one or more projects
97
+ // projects: undefined,
98
+
99
+ // Use this configuration option to add custom reporters to Jest
100
+ // reporters: undefined,
101
+
102
+ // Automatically reset mock state between every test
103
+ // resetMocks: false,
104
+
105
+ // Reset the module registry before running each individual test
106
+ // resetModules: false,
107
+
108
+ // A path to a custom resolver
109
+ // resolver: undefined,
110
+
111
+ // Automatically restore mock state between every test
112
+ // restoreMocks: false,
113
+
114
+ // The root directory that Jest should scan for tests and modules within
115
+ // rootDir: undefined,
116
+
117
+ // A list of paths to directories that Jest should use to search for files in
118
+ // roots: [
119
+ // "<rootDir>"
120
+ // ],
121
+
122
+ // Allows you to use a custom runner instead of Jest's default test runner
123
+ // runner: "jest-runner",
124
+
125
+ // The paths to modules that run some code to configure or set up the testing environment before each test
126
+ // setupFiles: [],
127
+
128
+ // A list of paths to modules that run some code to configure or set up the testing framework before each test
129
+ // setupFilesAfterEnv: [],
130
+
131
+ // A list of paths to snapshot serializer modules Jest should use for snapshot testing
132
+ // snapshotSerializers: [],
133
+
134
+ // The test environment that will be used for testing
135
+ testEnvironment: "node",
136
+
137
+ // Options that will be passed to the testEnvironment
138
+ // testEnvironmentOptions: {},
139
+
140
+ // Adds a location field to test results
141
+ // testLocationInResults: false,
142
+
143
+ // The glob patterns Jest uses to detect test files
144
+ // testMatch: [
145
+ // "**/__tests__/**/*.[jt]s?(x)",
146
+ // "**/?(*.)+(spec|test).[tj]s?(x)"
147
+ // ],
148
+
149
+ // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
150
+ // testPathIgnorePatterns: [
151
+ // "\\\\node_modules\\\\"
152
+ // ],
153
+
154
+ // The regexp pattern or array of patterns that Jest uses to detect test files
155
+ // testRegex: [],
156
+
157
+ // This option allows the use of a custom results processor
158
+ // testResultsProcessor: undefined,
159
+
160
+ // This option allows use of a custom test runner
161
+ // testRunner: "jasmine2",
162
+
163
+ // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
164
+ // testURL: "http://localhost",
165
+
166
+ // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
167
+ // timers: "real",
168
+
169
+ // A map from regular expressions to paths to transformers
170
+ // transform: undefined,
171
+
172
+ // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
173
+ // transformIgnorePatterns: [
174
+ // "\\\\node_modules\\\\"
175
+ // ],
176
+
177
+ // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
178
+ // unmockedModulePathPatterns: undefined,
179
+
180
+ // Indicates whether each individual test should be reported during the run
181
+ // verbose: undefined,
182
+
183
+ // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
184
+ // watchPathIgnorePatterns: [],
185
+
186
+ // Whether to use watchman for file crawling
187
+ // watchman: true,
188
+ };
@@ -0,0 +1,13 @@
1
+ import { FastifyReply, FastifyRequest } from 'fastify'
2
+
3
+ export async function user(req: FastifyRequest, reply: FastifyReply) {
4
+ reply.send(req.user || {})
5
+ }
6
+
7
+ export async function isAdmin(req: FastifyRequest, reply: FastifyReply) {
8
+ reply.send({ isAdmin: (req.user?.roles || []).includes('admin') || false })
9
+ }
10
+
11
+ export async function demo(req: FastifyRequest, reply: FastifyReply) {
12
+ reply.send({ demo: true })
13
+ }
@@ -0,0 +1,98 @@
1
+ export default {
2
+ config: {
3
+ title: 'Useful functions',
4
+ description: 'Useful functions',
5
+ controller: 'controller',
6
+ tags: ['user', 'code'], // swagger
7
+ enable: true,
8
+ deprecated: false, // swagger
9
+ version: false // swagger
10
+ },
11
+ routes: [
12
+ {
13
+ method: 'GET',
14
+ path: '/',
15
+ roles: [],
16
+ handler: 'me.user',
17
+ middlewares: ['global.isAuthenticated'],
18
+ config: {
19
+ enable: true,
20
+ title: 'Me title', // swagger summary
21
+ description: 'Me description', // swagger
22
+ tags: ['user', 'code'], // swagger
23
+ deprecated: false, // swagger
24
+ version: false, // swagger
25
+ response: {
26
+ 403: {
27
+ description: 'Successful response',
28
+ type: 'object',
29
+ properties: {
30
+ hello: { type: 'string' }
31
+ }
32
+ },
33
+ 200: {
34
+ description: 'Default response',
35
+ type: 'object',
36
+ properties: {
37
+ id: { type: 'number' }
38
+ }
39
+ }
40
+ } // swagger
41
+ }
42
+ },
43
+ {
44
+ method: 'GET',
45
+ path: '/is-admin',
46
+ roles: [],
47
+ handler: 'me.isAdmin',
48
+ middlewares: ['global.isAuthenticated'],
49
+ config: {
50
+ title: 'Admin',
51
+ description: 'Admin',
52
+ enable: true,
53
+ deprecated: false,
54
+ version: false
55
+ }
56
+ },
57
+ {
58
+ method: 'GET',
59
+ path: '/demo',
60
+ roles: [],
61
+ handler: 'me.demo',
62
+ middlewares: ['global.isAdmin'],
63
+ config: {
64
+ enable: true,
65
+ title: 'Me title', // swagger summary
66
+ description: 'Me description', // swagger
67
+ tags: ['user', 'code'], // swagger
68
+ deprecated: false, // swagger
69
+ version: false, // swagger
70
+ params: {
71
+ type: 'object',
72
+ properties: {
73
+ id: {
74
+ type: 'string',
75
+ description: 'user id'
76
+ }
77
+ }
78
+ }, // swagger
79
+ response: {
80
+ 201: {
81
+ description: 'Successful response',
82
+ type: 'object',
83
+ properties: {
84
+ hello: { type: 'string' }
85
+ }
86
+ },
87
+ 200: {
88
+ description: 'Default response',
89
+ type: 'object',
90
+ properties: {
91
+ foo: { type: 'string' }
92
+ }
93
+ }
94
+ } // swagger
95
+ }
96
+ }
97
+ ]
98
+ }
@@ -0,0 +1,11 @@
1
+ 'use strict'
2
+
3
+ import { ApolloFastifyContextFunction } from '@as-integrations/fastify'
4
+
5
+ export interface MyContext {
6
+ greeting: string
7
+ }
8
+
9
+ export const myContextFunction: ApolloFastifyContextFunction<MyContext> = async () => ({
10
+ greeting: 'Hello World!! ' + new Date().getTime()
11
+ })
@@ -0,0 +1,11 @@
1
+ 'use strict'
2
+
3
+ import { MyContext } from './context'
4
+
5
+ const resolvers = {
6
+ Query: {
7
+ helloWorld: (parent: any, args: any, context: MyContext, info: any) => context.greeting
8
+ }
9
+ }
10
+
11
+ export default resolvers
@@ -0,0 +1,9 @@
1
+ 'use strict'
2
+
3
+ const typeDefs = `
4
+ type Query {
5
+ helloWorld: String!
6
+ }
7
+ `
8
+
9
+ export default typeDefs
@@ -0,0 +1,25 @@
1
+ export {}
2
+
3
+ // additional roles
4
+ declare global {
5
+ enum RoleKey {}
6
+ // customer = 'customer'
7
+ }
8
+
9
+ export const roles: Role[] = [
10
+ {
11
+ code: 'public',
12
+ name: 'Public',
13
+ description: 'Public role'
14
+ },
15
+ {
16
+ code: 'admin',
17
+ name: 'Admin',
18
+ description: 'Admin role'
19
+ },
20
+ {
21
+ code: 'backoffice',
22
+ name: 'Backoffice',
23
+ description: 'Backoffice role'
24
+ }
25
+ ]