|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const boom = require('@hapi/boom'); |
| 4 | +const schema = require('screwdriver-data-schema'); |
| 5 | +const validator = require('screwdriver-template-validator').parsePipelineTemplate; |
| 6 | +const templateSchema = schema.api.templateValidator; |
| 7 | + |
| 8 | +module.exports = () => ({ |
| 9 | + method: 'POST', |
| 10 | + path: '/pipeline/template', |
| 11 | + options: { |
| 12 | + description: 'Create a new pipeline template', |
| 13 | + notes: 'Create a specific pipeline template', |
| 14 | + tags: ['api', 'pipelineTemplate'], |
| 15 | + auth: { |
| 16 | + strategies: ['token'], |
| 17 | + scope: ['build'] |
| 18 | + }, |
| 19 | + |
| 20 | + handler: async (request, h) => { |
| 21 | + const { pipelineTemplateVersionFactory, pipelineTemplateFactory } = request.server.app; |
| 22 | + |
| 23 | + const config = await validator(request.payload.yaml); |
| 24 | + |
| 25 | + if (config.errors.length > 0) { |
| 26 | + throw boom.badRequest(`Template has invalid format: ${config.errors.length} error(s).`, config.errors); |
| 27 | + } |
| 28 | + |
| 29 | + const pipelineTemplate = await pipelineTemplateFactory.get({ |
| 30 | + name: config.template.name, |
| 31 | + namespace: config.template.namespace |
| 32 | + }); |
| 33 | + |
| 34 | + const { isPR, pipelineId } = request.auth.credentials; |
| 35 | + |
| 36 | + // If template name exists, but this build's pipelineId is not the same as template's pipelineId |
| 37 | + // Then this build does not have permission to publish |
| 38 | + if (isPR || (pipelineTemplate && pipelineId !== pipelineTemplate.pipelineId)) { |
| 39 | + throw boom.forbidden('Not allowed to publish this template'); |
| 40 | + } |
| 41 | + |
| 42 | + const template = await pipelineTemplateVersionFactory.create( |
| 43 | + { |
| 44 | + ...config.template, |
| 45 | + pipelineId |
| 46 | + }, |
| 47 | + pipelineTemplateFactory |
| 48 | + ); |
| 49 | + |
| 50 | + const location = new URL( |
| 51 | + `${request.path}/${template.id}`, |
| 52 | + `${request.server.info.protocol}://${request.headers.host}` |
| 53 | + ).toString(); |
| 54 | + |
| 55 | + return h.response(template.toJson()).header('Location', location).code(201); |
| 56 | + }, |
| 57 | + validate: { |
| 58 | + payload: templateSchema.input |
| 59 | + } |
| 60 | + } |
| 61 | +}); |
0 commit comments